Thread Creation in Rust

Thread creation in Rust could be done with thread::spawn function imported from the standard library std::thread. A closure, that includes statements needed to be executed, should be passed to the function. The function will return the type JoinHandle.

let print_val = String::from("hi");
let handle = thread::spawn(move || {
		println!("Message: {}", print_val);
});

Note: move is necessary in order to move the ownership of a variable from the outer scope to the thread scope. This will avoid 202112061109# as the thread created truly owns the variable passed into its scope.

After the creation of thread, they will execute their body in arbitrary time. This means that the main thread could end first before the completion of execution of all threads and terminate all of them without waiting. To let the main thread waits for other threads, use the method join provided by the type JoinHandle.

handle.join().unwrap();

To establish a communication mean between multiple threads, see 202207171825#.

Links to this page
  • Rust Channel

    Since Rust uses the model of message passing (same as 202203021733) as a mean of thread synchronisation, a channel must be established for the threads to communicate with each other. The standard library std::sync::mpsc (mpsc stand for multiple producer single consumer#) provides the function mpsc::channel that could create a channel, which will define transmitter(s) (the one that sends messages) and receiver (the one that receives messages). The return type will be a tuple, the first element represents transmitter(s), the second element represents receiver. Combining with #202207171541, we can send a message from a thread (via transmitter’s method send) to the main thread (via receiver’s method recv or try_recv).

  • Mutex in Rust

    If there is a need to share the data across multiple #threads, 202112061109# will inevitably happen. The need for a mutex (mutual exclusion lock) arises, so that only the one that obtained the lock can modify the data state at a time, where others will queue up and wait for the lock to be released. Rust provides Mutex type through the standard library std::sync::Mutex. Acquiring the lock from Mutex can be done by simply calling the function lock. However, there is a need to handle the error that could arise if the current owner of the mutex panics during its execution.

  • Multithreading Management
#multithreading #rust