Created
November 15, 2015 06:11
-
-
Save anonymous/2808abf426a9e3f36d68 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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::{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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment