Created
January 13, 2015 09:24
-
-
Save grigio/d1c716bfd532e5977965 to your computer and use it in GitHub Desktop.
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
// 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