Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. class CountingSemaphore {
  2.        int count;
  3.        BinarySemaphore m(1), b(0); // m is a mutex
  4.       public:
  5.        CountingSemaphore(int initial_value) {count = initial_value;}
  6.        
  7.        void down() {
  8.          m.down();
  9.          count--;
  10.          if (count < 0) { // max threads are already active
  11.            m.up();
  12.            b.down(); // block this thread
  13.          }
  14.          m.up();
  15.        }
  16.  
  17.        void up() {
  18.          m.down();
  19.          count++;
  20.          if (count <= 0) // threads are waiting on this CountingSemaphore
  21.            b.up(); // signal one thread to wake, which will also call m.up()
  22.          else
  23.            m.up();
  24.        }
  25.      }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement