Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate rand;
- use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
- use std::thread;
- use std::time::Duration;
- use rand::{thread_rng, Rng};
- static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
- fn inc(id: u8) {
- let mut rng = thread_rng();
- let wait_ms = rng.gen_range(1, 500);
- thread::sleep(Duration::from_millis(wait_ms));
- let my_count = COUNTER.fetch_add(1, Ordering::SeqCst);
- println!("Thread {}, my count: {}", id, my_count);
- }
- fn main() {
- let mut handles = Vec::new();
- for i in 0..5 {
- handles.push(thread::spawn(move || inc(i)));
- }
- for handle in handles {
- let _ = handle.join();
- }
- }
Add Comment
Please, Sign In to add comment