Using binary semaphores as a counting semaphore?

From the sounds of it, you have to make your own semaphore class. You could have a private member variable to increment/decrement as with a semaphore, and have a binary semaphore private member to make those increments/decrements atomic. Have release/acquire public methods that will do the inc/dec.

When the counter goes to zero release the binary semaphore, and wait on a condition (another mutex). When another thread calls release on your semaphore class, and the counter is now above zero, signal to all those waiting on the condition to wake up, and try to reaquire your semaphore.

From the sounds of it, you have to make your own semaphore class. You could have a private member variable to increment/decrement as with a semaphore, and have a binary semaphore private member to make those increments/decrements atomic. Have release/acquire public methods that will do the inc/dec.

When the counter goes to zero release the binary semaphore, and wait on a condition (another mutex). When another thread calls release on your semaphore class, and the counter is now above zero, signal to all those waiting on the condition to wake up, and try to reaquire your semaphore. Hope this helps and makes sense.

As @Alexander Kondratskiy pointed out, it sounds like you are supposed to use a binary semaphore in order to implement a real semaphore. Here's part of a Sempahore implementation from one of my personal projects, you still need to fill in the blanks... #ifndef SEMAPHORE_20100517_H_ #define SEMAPHORE_20100517_H_ #include #include class Semaphore { public: explicit Semaphore(int count); public: void wait(); void signal(); private: void block(); void unblock(); private: int value_; std::queue waitlist_; mutex mutex_; }; #endif Semaphore::Semaphore(int count) : value_(count) { assert(count >= 0); } void Semaphore::wait() { // same as your P() mutex_.lock(); if(--value_ } void Semaphore::unblock() { // Fill in the blanks! // pull someone from the queue and unblock them!

}.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions