- channel
- send
- recv
- move
Threads with messages
- We can faciliate communication between the main thread and the spawned thread.
- In this example the spawned thread is sending a message to the main thread.
- The move keyword tells Rust that the variables declared before spawning that are also used in the spawned code need to be moved. (tx in this case)
- recv is blocking the main thread.
examples/threads/threads-messages/src/main.rs
use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("Hello"); tx.send(val).unwrap(); for i in 1..=10 { thread::sleep(Duration::from_millis(1)); tx.send(i.to_string()).unwrap(); } println!("Spawned thread ends"); }); let received = rx.recv().unwrap(); println!("Got: {}", received); // complex way for reveiving for _j in 1..=5 { let received = rx.recv().unwrap(); println!("Got: {}", received); } println!(); // simple code for receiving for received in rx { println!("Got: {}", received); } println!(); println!("Main thread ends"); }
Got: Hello Got: 1 Got: 2 Got: 3 Got: 4 Got: 5 Got: 6 Got: 7 Got: 8 Got: 9 Spawned thread ends Got: 10 Main thread ends