Skip to content

Instantly share code, notes, and snippets.

@lorkki
Last active February 25, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorkki/e7386df8fff186b3e473994e9d31bee0 to your computer and use it in GitHub Desktop.
Save lorkki/e7386df8fff186b3e473994e9d31bee0 to your computer and use it in GitHub Desktop.
thread examples
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]);
}
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