我们用条件变量和互斥量去封装信号量!
#include<mutex>
#include<condition_variable>
using namespace std;
class Semaphore
{
public:
Semaphore(int value = 1) :count(value) {}
~Semaphore() {}
Semaphore(const Semaphore&) = delete; // c11标准
Semaphore& operator=(const Semaphore&) = delete; // c11标准
void P()//P操作的实现
{
unique_lock<mutex> locker(mtx);
if (--count < 0)
{
cv.wait(locker); //挂起阻塞
}
}
void V()//V操作的实现
{
unique_lock<mutex> locker(mtx);
if (++count <= 0)
{
cv.notify_one();//唤醒线程
}
}
private:
int count;//计数器
std::mutex mtx;//互斥量
std::condition_variable cv;//条件变量
};