Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. use std::sync::{Condvar, Mutex};
  2.  
  3. pub
  4. struct Semaphore {
  5. mutex: Mutex<i32>,
  6. cvar: Condvar,
  7. }
  8.  
  9. impl Semaphore {
  10. pub
  11. fn new (count: u16) -> Self
  12. {
  13. Semaphore {
  14. mutex: Mutex::new(count as i32),
  15. cvar: Condvar::new(),
  16. }
  17. }
  18.  
  19. pub
  20. fn dec (&self)
  21. {
  22. let mut lock = self.mutex.lock().unwrap();
  23. *lock -= 1;
  24. while *lock < 0 {
  25. lock = self.cvar.wait(lock).unwrap();
  26. }
  27. }
  28.  
  29. pub
  30. fn inc (&self)
  31. {
  32. let mut lock = self.mutex.lock().unwrap();
  33. *lock += 1;
  34. if *lock <= 0 {
  35. self.cvar.notify_one();
  36. }
  37. }
  38. }
  39.  
  40. fn main ()
  41. {
  42. const N: u32 = 10;
  43. let sem1 = Semaphore::new(0);
  44. let sem2 = Semaphore::new(1); // thread 2 said go
  45. ::crossbeam::scope(|scope| {
  46. // thread 1
  47. scope.spawn(|_| (0 .. N).for_each(|_| {
  48. sem2.dec(); // wait for thd 2 to say go
  49. println!("First");
  50. sem1.inc(); // say go
  51. }));
  52.  
  53. // thread 2
  54. scope.spawn(|_| (0 .. N).for_each(|_| {
  55. sem1.dec(); // wait for thd 1 to say go
  56. println!("Second");
  57. sem2.inc(); // say go
  58. }));
  59. }).expect("Some thread panicked");
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement