Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CountingSemaphore {
- int count;
- BinarySemaphore m(1), b(0); // m is a mutex
- public:
- CountingSemaphore(int initial_value) {count = initial_value;}
- void down() {
- m.down();
- count--;
- if (count < 0) { // max threads are already active
- m.up();
- b.down(); // block this thread
- }
- m.up();
- }
- void up() {
- m.down();
- count++;
- if (count <= 0) // threads are waiting on this CountingSemaphore
- b.up(); // signal one thread to wake, which will also call m.up()
- else
- m.up();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement