rust-book/threads/src/main.rs

69 lines
1.5 KiB
Rust
Raw Normal View History

2019-02-05 14:02:40 -05:00
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
fn basic_thread_usage() {
let v = vec![1, 2, 3];
// Move is a keyword, not a parameter, it gives
// ownership of closure values to the thread
let handle = thread::spawn(move|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
println!("Here's a vector: {:?}", v);
thread::sleep(Duration::from_millis(1));
}
});
handle.join().unwrap();
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
fn messages_example() {
let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx1.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
fn main() {
basic_thread_usage();
messages_example();
}