Skip to content

Instantly share code, notes, and snippets.

@drbawb
Last active August 29, 2015 14:03
Show Gist options
  • Save drbawb/6a82013b2823d732664b to your computer and use it in GitHub Desktop.
Save drbawb/6a82013b2823d732664b to your computer and use it in GitHub Desktop.
Data Race Example
use std::io::timer::sleep;
use std::sync::{Arc,RWLock};
fn main() {
println!("running channels: ");
channels();
println!("running locks: ");
locks();
}
// uses write locks as a sync mechanism.
fn locks() {
let threads = 10u;
let count = 50u;
let x = Arc::new(RWLock::new(1u));
for _ in range(0u, threads) {
let my_x = x.clone(); // copy the Arc{} for task we're about to start
spawn(proc() {
for _ in range(0u, count) {
sleep(1);
(*my_x.write()) += 1; // lock and increment.
}
});
}
sleep(1000);
println!("Result is {}", (*x.read()))
}
// uses channels as a synchronization mechanism
fn channels() {
let threads = 10u;
let count = 50u;
let (acc_tx, acc_rx) = channel();
for _ in range(0u, threads) {
let my_tx = acc_tx.clone();
spawn(proc() {
for _ in range (0u, count) {
sleep(1);
my_tx.send(1);
}
});
}
drop(acc_tx); // drop the unused sender.
// when the 10 threads are finished there will be
// no senders left: and the channel will close.
let mut acc = 0u;
loop {
match acc_rx.recv_opt() {
Ok(inc_by) => { acc += inc_by }, // got a value from the channel, incr. the accumulator
Err(_) => { break; }, // channel is closed
};
}
println!("{}", acc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment