Multithreading in Rust

Imagine you’re organizing an expedition. You have a group of brave explorers ready and waiting for your command. In the world of Rust, these explorers are like threads, and you are the programmer using the std::thread module.

Gathering the Explorers

You can summon a new explorer (thread) using the std::thread::spawn function. Just give them a map (closure), and they’ll set off on their adventure (execute code).

use std::thread;

use std::time::Duration;

let handle = thread::spawn(|| {

    for i in 1..10 {

        println!("hi number {} from the spawned thread!", i);

        thread::sleep(Duration::from_millis(1));

    }

});

Waiting for the Explorers to Return

Once the explorer sets off, you get a JoinHandle. This is like a magical communicator that you can use to wait for the explorer to return and hear their report (get the result).

handle.join().unwrap();

In Rust, each explorer corresponds to a thread in the real world. It’s as if each explorer has their own path and goal, and they can explore independently. This is different from some other languages (like Go or Java), where explorers might need to share some paths and goals.

Sharing the Treasure

Sometimes, the explorers need to share some treasure (state). Rust provides some magical tools, like std::sync::Mutex and std::sync::Arc, which can help the explorers to share and modify the treasure safely.

use std::sync::{Arc, Mutex};

use std::thread;

let counter = Arc::new(Mutex::new(0));

let mut handles = vec![];

for _ in 0..10 {

    let counter = Arc::clone(&counter);

    let handle = thread::spawn(move || {

        let mut num = counter.lock().unwrap();

        *num += 1;

    });

    handles.push(handle);

}

for handle in handles {

    handle.join().unwrap();

}

println!("Result: {}", *counter.lock().unwrap());

Published by endecoder

MY shitting learning experience

Leave a comment