正如@Alexander Kondratskiy指出的那样,这听起来像是你应该使用二进制信号量来实现一个真正的信号量。这里有一个Sempahore实施的一部分,从我个人的一个项目,你仍然需要填补空白...
#ifndef SEMAPHORE_20100517_H_
#define SEMAPHORE_20100517_H_
#include <Scheduler.h>
#include <queue>
class Semaphore {
public:
explicit Semaphore(int count);
public:
void wait();
void signal();
private:
void block();
void unblock();
private:
int value_;
std::queue<scheduler::thread> waitlist_;
mutex mutex_;
};
#endif
Semaphore::Semaphore(int count) : value_(count) {
assert(count >= 0);
}
void Semaphore::wait() { // same as your P()
mutex_.lock();
if(--value_ < 0) {
mutex_.unlock(); // we have to give up the lock if we are going to block
block();
mutex_.lock(); // reacquire the lock for symmetry when we exit
}
mutex_.unlock();
}
void Semaphore::signal() { // same as your V()
mutex_.lock();
if(++value_ <= 0) {
unblock();
}
mutex_.unlock();
}
void Semaphore::block() {
// Fill in the blanks!
// block the current thread and add it to the queue!
}
void Semaphore::unblock() {
// Fill in the blanks!
// pull someone from the queue and unblock them!
}
提示:1)请记住,一个互斥量大致为二进制信号量,后期计数为1. 2)每次调用block()时,都可以创建一个新的二进制信号量,并将该信号量放入队列中。然后,实际的块/解锁操作变得微不足道。 – 2012-03-06 10:39:45