Last active
February 25, 2019 17:04
-
-
Save lorkki/e7386df8fff186b3e473994e9d31bee0 to your computer and use it in GitHub Desktop.
thread examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
fn main() { | |
let mut list = Vec::new(); | |
let my_thread = thread::spawn(move || { | |
add_elements_to(&mut list); | |
list | |
}); | |
let list = my_thread.join().unwrap(); | |
println!("{:?}", &list); | |
} | |
fn add_elements_to(list: &mut Vec<u32>) { | |
list.append(&mut vec![1, 2, 3]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::mpsc; | |
use std::thread; | |
fn main() { | |
let (tx, rx) = mpsc::channel(); | |
spawn_workers(tx); | |
let result: u32 = rx.iter().sum(); | |
println!("Result: {}", result); | |
} | |
fn spawn_workers(tx: mpsc::Sender<u32>) { | |
for i in 1..=10 { | |
let tx_inner = tx.clone(); | |
thread::spawn(move || { | |
tx_inner.send(i) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment