条件变量
P V
二元信号量(不是零就是一)
binary_semaphore semp=1;
binary_semaphore sems=1;
semp.acquire();1->0
sems.release();0->1;
生产者与消费者
class MySemaphore//实现P操作和V操作
{
public:
MySemaphore(int val=1):count(1){}
void P()//acquire()
{
std::unique_lock<std::mutex> lck(mtk);
if (--count < 0)
{
cv.wait(lck);
}
}
void V()//release
{
std::unique_lock<std::mutex> lck(mtk);
if (++count <= 0)
{
cv.notify_one();
}
}
private:
int count;
std::mutex mtk;
std::condition_variable cv;
};
int g_num = 0;
MySemaphore semp(1);
MySemaphore sems(0);
void P(int id)//生产者
{
for (int i = 0;i < 10;++i)
{
semp.P();
{
g_num = i;
cout << "P : " << g_num << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
sems.V();
}
}
void S(int id)//消费者
{
for (int i = 0;i < 10;++i)
{
sems.P();
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
cout << "S : " << g_num << endl;
}
semp.V();
}
}
int main()
{
std::thread tha(P,1);
std::thread ths(S,1);
tha.join();
ths.join();
return 0;
}