Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::{Condvar, Mutex};
- pub
- struct Semaphore {
- mutex: Mutex<i32>,
- cvar: Condvar,
- }
- impl Semaphore {
- pub
- fn new (count: u16) -> Self
- {
- Semaphore {
- mutex: Mutex::new(count as i32),
- cvar: Condvar::new(),
- }
- }
- pub
- fn dec (&self)
- {
- let mut lock = self.mutex.lock().unwrap();
- *lock -= 1;
- while *lock < 0 {
- lock = self.cvar.wait(lock).unwrap();
- }
- }
- pub
- fn inc (&self)
- {
- let mut lock = self.mutex.lock().unwrap();
- *lock += 1;
- if *lock <= 0 {
- self.cvar.notify_one();
- }
- }
- }
- fn main ()
- {
- const N: u32 = 10;
- let sem1 = Semaphore::new(0);
- let sem2 = Semaphore::new(1); // thread 2 said go
- ::crossbeam::scope(|scope| {
- // thread 1
- scope.spawn(|_| (0 .. N).for_each(|_| {
- sem2.dec(); // wait for thd 2 to say go
- println!("First");
- sem1.inc(); // say go
- }));
- // thread 2
- scope.spawn(|_| (0 .. N).for_each(|_| {
- sem1.dec(); // wait for thd 1 to say go
- println!("Second");
- sem2.inc(); // say go
- }));
- }).expect("Some thread panicked");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement