目录
版本1 双信号量版
版本二 单信号量版
版本三 信号量版
共享资源是100个数字(一个计数器的++ 由两个进程争抢完成)
首先访问临界资源(对计数器++操作)是肯定的要加锁的,交替打印肯定要用条件变量来互相唤醒 互相锁死
也可以使用信号量对临界资源做判断
所以使用wait的时候不需要释放锁
版本1 双信号量版
唤醒对方条件不满足的信号量
//双条件变量版本
void thread1() {
while (true) {
unique_lock<mutex> locker(mut); //会自动解锁
if (g_nums % 2 == 1 && g_nums <= num)
{
cout << "Thread1:" << g_nums << endl;
g_nums++;
}
cond2.notify_one();
cond1.wait(locker);
if (g_nums >= num+1)
break;
}
cout << "1 done"<< endl;
cond2.notify_one();
}
void thread2() {
while (true) {
unique_lock<mutex> locker(mut);
if (g_nums % 2 == 0 && g_nums <= num)
{
cout << "Thread2:" << g_nums << endl;
g_nums++;
}
cond1.notify_one();
cond2.wait(locker);
if (g_nums >= num + 1)
break;
}
cout << "2 done" << endl;
cond1.notify_one();
}
int main() {
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
cout << "done" << endl;
return 0;
}
版本二 单信号量版
//单条件变量版本
void thread1()
{
while (true)
{
unique_lock<mutex> lock(mut);
if (g_nums % 2 == 1 && g_nums <= num)
{
cout << "thread 1:" << g_nums ++<< endl;
}
cond.notify_one(); //唤醒另一个进程
cond.wait(lock); //把当前的进程锁住
if (g_nums >= num+1)
break;
}
cout << "1 done"<< endl;
cond.notify_one();
}
void thread2() {
while (1) {
unique_lock<mutex> locker(mut);
if (g_nums % 2 == 0 && g_nums <= num)
{
cout << "Thread2:" << g_nums << endl;
g_nums++;
}
cond.notify_one();
cond.wait(locker);
if (g_nums >= num+1)
break;
}
cout << "2 done" << endl;
cond.notify_one();
}
int main() {
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
cout << "done" << endl;
return 0;
}
版本三 信号量版
C++在语言级别并没有支持semaphore
我们自己实现一个
#pragma once
#include <iostream>
#include <mutex>
#include <condition_variable>
using namespace std;
class semaphore {
public:
semaphore(int num=0)
:count(num)
{
}
~semaphore()
{}
void single() //V
{
unique_lock<mutex> lock(mtx);
if (++count <= 0)
cond.notify_one();
}
void wait() //p
{
unique_lock<mutex> lock(mtx);
if (--count < 0)
cond.wait(lock);
}
private:
int count;
mutex mtx;
condition_variable cond;
};
然后可以正常使用
//信号量版本
void thread1()
{
while (true)
{
if (g_nums % 2 == 1 && g_nums <= num)
{
cout << "thread 1:" << g_nums++ << endl;
smp1.single();
}
smp2.wait();
//cond.notify_one(); //唤醒另一个进程
//cond.wait(lock); //把当前的进程锁住
if (g_nums >= num + 1)
break;
}
cout << "1 done" << endl;
smp1.single();
}
void thread2() {
while (true) {
if (g_nums % 2 == 0 && g_nums <= num)
{
cout << "Thread2:" << g_nums ++<< endl;
smp2.single();
}
smp1.wait();
if (g_nums >= num+1)
break;
}
cout << "2 done" << endl;
smp2.single();
}
int main()
{
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
cout << "done" << endl;
return 0;
}