-
-
Save FranklinChen/5ef24c6742dd4d84b697 to your computer and use it in GitHub Desktop.
Revisions
-
There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ use std::sync::{Arc, Mutex}; use std::thread; struct Toaster { count: u32 } impl Toaster { fn new() -> Toaster { Toaster { count: 0 } } } fn main() { let toaster = Arc::new(Mutex::new(Toaster::new())); let threads: Vec<_> = (0..3) .map(|_| { let toaster = toaster.clone(); thread::spawn(move || { // load and increment toaster's count, atomically let mut t = toaster.lock().unwrap(); let index = t.count; t.count += 1; println!("My index is {:?}", index); }) }) .collect(); for t in threads { t.join().unwrap(); } }