Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shared via Rust Playground
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();
}
}
@FranklinChen

This comment has been minimized.

Copy link
Owner Author

FranklinChen commented Nov 15, 2015

Solution 3 to exercise 3 of http://ncameron.org/oopsla15.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.