1. 信号量的定义
2. 使用std::mutext与std::condition_variables实现信号量
代码来自:https://zhuanlan.zhihu.com/p/462668211
#ifndef _SEMAPHORE_H
#define _SEMAPHORE_H
#include <mutex>
#include <condition_variable>
using namespace std;class Semaphore
{
public:Semaphore(long count = 0) : count(count) {}//V操作,唤醒void signal(){unique_lock<mutex> unique(mt);++count;//原文这块有点问题,shanql//if (count <= 0) // cond.notify_one();cond.notify_one();}//P操作,阻塞void wait(){unique_lock<mutex> unique(mt);--count;//if (count < 0) //原文这块有点问题,shanqlwhile( count < 0 )cond.wait(unique);}private:mutex mt;condition_variable cond;long count;
};
#endif