正如@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