Skip to content

Instantly share code, notes, and snippets.

@FranklinChen
Forked from anonymous/playground.rs
Created November 15, 2015 06:11
Show Gist options
  • Select an option

  • Save FranklinChen/5ef24c6742dd4d84b697 to your computer and use it in GitHub Desktop.

Select an option

Save FranklinChen/5ef24c6742dd4d84b697 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Nov 15, 2015.
    34 changes: 34 additions & 0 deletions playground.rs
    Original 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();
    }
    }