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#.