Skip to content

Instantly share code, notes, and snippets.

@FranklinChen
Forked from anonymous/playground.rs
Created November 15, 2015 06:11
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 FranklinChen/5ef24c6742dd4d84b697 to your computer and use it in GitHub Desktop.
Save FranklinChen/5ef24c6742dd4d84b697 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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