Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. use std::sync::{Arc, Mutex};
  2. use std::thread;
  3. use std::time;
  4.  
  5. struct Context{
  6. threads_running_count: Arc<Mutex<i32>>,
  7. }
  8.  
  9. fn do_stuff(thread_number: i32, ctx: &mut Context){
  10. let mut attempts = 0;
  11. while true{
  12. thread::sleep(time::Duration::from_millis(10));
  13. let mutex_clone = ctx.threads_running_count.clone();
  14. let mut running = ctx.threads_running_count.lock().unwrap();
  15. if *running > 10 {
  16. attempts += 1;
  17. continue;
  18. }
  19.  
  20. // we have a lock on the mutex and we know that zero threads are running
  21. thread::spawn(move ||{
  22. thread::sleep(time::Duration::from_millis(1000));
  23. println!("hi, i'm thread number {}, took me {} attempts to start", thread_number, attempts);
  24. // declare ourselves done
  25. let mut running = mutex_clone.lock().unwrap();
  26. *running -= 1;
  27. }
  28. );
  29. *running += 1;
  30. break;
  31. }
  32. }
  33.  
  34. fn main(){
  35. let mut ctx = Context { threads_running_count: Arc::new(Mutex::new(0)) };
  36. for i in 0..100{
  37. do_stuff(i, &mut ctx);
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement