We’ve used recv in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate.
Then I have a try to implement it with try_recv
.
We’ve used recv in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate.
Then I have a try to implement it with try_recv
.
use std::thread; | |
use std::sync::mpsc; | |
use std::time; | |
fn main() { | |
let (tx, rx) = mpsc::channel(); | |
thread::spawn(move || { | |
let val = String::from("hi"); | |
thread::sleep(time::Duration::from_millis(100)); | |
tx.send(val).unwrap(); | |
}); | |
loop { | |
match rx.try_recv() { | |
Ok(r) => { | |
println!("Got: {}", r); | |
break; | |
}, | |
Err(err) => { | |
println!("Waiting..."); | |
thread::sleep(time::Duration::from_millis(10)); | |
} | |
} | |
} | |
} |