此文作为笔记,记录代码片段。
说明
Semaphore 构造函数,count表示最多几个线程同时运行。
Wait 等待可执行线程出现
Signal 已准备好,请求执行
代码片段
class Semaphore {
public:
Semaphore(long count = 0)
: count_(count) {
}
void Signal() {
std::unique_lock<std::mutex> lock(mutex_);
++count_;
//lock.unlock();
cv_.notify_one();
}
void Wait() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [=] { return count_ > 0; });
--count_;
}
void Reset(long count = 0) {
count_ = count;
}
private:
std::mutex mutex_;
std::condition_variable cv_;
long count_;
};
#endif