Skip to content

Instantly share code, notes, and snippets.

@grigio
Created January 13, 2015 09:24
Show Gist options
  • Save grigio/d1c716bfd532e5977965 to your computer and use it in GitHub Desktop.
Save grigio/d1c716bfd532e5977965 to your computer and use it in GitHub Desktop.
// Ported to rust 1.0.0-dev
// latest version is https://github.com/grigio/fun-with-threads/blob/master/rust_counter_atomics.rs
use std::sync::Arc;
use std::sync::atomic::AtomicUint;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::mpsc::channel;
use std::thread::Thread;
const NUM_THREADS: usize = 20;
const NUM_INCREMENTS: usize = 10000000us;
fn main() {
let counter = Arc::new(AtomicUint::new(0));
let (tx, rx) = channel();
for _ in range(0us, NUM_THREADS) {
let (counter, tx) = (counter.clone(), tx.clone());
Thread::spawn(move || {
for _ in range(0us, NUM_INCREMENTS) {
counter.fetch_add(1, Relaxed);
}
tx.send(());
});
}
// Wait for threads to finish
for _ in range(0us, NUM_THREADS) { rx.recv(); }
println!("{}" , counter.load(Relaxed));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment