Concurrency and Threads
Rust makes concurrency safe using threads and channels.
Spawning a Thread
use std::thread;
let handle = thread::spawn(|| {
for i in 1..5 {
println!("hi from the spawned thread: {}", i);
}
});
handle.join().unwrap();
Channels
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(String::from("Hello"))?;
println!("Received: {}", rx.recv()?);
Use Arc
and Mutex
for shared mutable state across threads.