Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::{Arc, Mutex};
- use std::thread;
- use std::time;
- struct Context{
- threads_running_count: Arc<Mutex<i32>>,
- }
- fn do_stuff(thread_number: i32, ctx: &mut Context){
- let mut attempts = 0;
- while true{
- thread::sleep(time::Duration::from_millis(10));
- let mutex_clone = ctx.threads_running_count.clone();
- let mut running = ctx.threads_running_count.lock().unwrap();
- if *running > 10 {
- attempts += 1;
- continue;
- }
- // we have a lock on the mutex and we know that zero threads are running
- thread::spawn(move ||{
- thread::sleep(time::Duration::from_millis(1000));
- println!("hi, i'm thread number {}, took me {} attempts to start", thread_number, attempts);
- // declare ourselves done
- let mut running = mutex_clone.lock().unwrap();
- *running -= 1;
- }
- );
- *running += 1;
- break;
- }
- }
- fn main(){
- let mut ctx = Context { threads_running_count: Arc::new(Mutex::new(0)) };
- for i in 0..100{
- do_stuff(i, &mut ctx);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement