-
-
Save grigio/9ca208842bcdd3391945 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 0.13.0-nightly but it doesn't seem to work as expected | |
use std::time::duration::Duration; | |
use std::sync::{Arc,RWLock}; | |
use std::thread::Thread; | |
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 | |
Thread::spawn(move || { | |
for _ in range(0u, count) { | |
Duration::seconds(1); | |
(*my_x.write()) += 1; // lock and increment. | |
} | |
}).detach(); | |
} | |
Duration::seconds(1); | |
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(); | |
Thread::spawn(move || { | |
for _ in range (0u, count) { | |
Duration::seconds(1); | |
my_tx.send(1); | |
} | |
}).detach(); | |
} | |
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