需要先看前文:死锁的产生_御坂美琴1的博客-CSDN博客
对两个资源使用一把锁。即小朋友玩敲鼓的时候会同时拿走鼓和鼓槌。
如图:
可以看到“线程1执行了,但是线程2没有执行,还在被阻塞着。为什么线程1运行完毕,线程2还没有开始运行?
因为此时使用了lock函数,lock是需要自己手动开锁的。
增加如下语句即可:
图片中的代码不严谨,因为它考虑的是线程1先进行,修改后如下:
全部代码如下:
#include<iostream>
#include<thread>
#include<mutex>
#include<windows.h>
using namespace std;
void thread1();
void thread2();
mutex mx1;
mutex mx2;
int a = 100;
int b = 200;
int main(void)
{
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
return 0;
}
void thread1()
{
cout << "thread1 is running" << endl;
lock(mx1,mx2);//对mx1和mx2同时加锁
lock_guard<mutex> guard1(mx1, adopt_lock);//adopt_lock自适应上锁,如果上过锁了就不会重复上锁
lock_guard<mutex> guard2(mx2, adopt_lock);
cout << "thread1's num is " << a << endl;
Sleep(1000);
cout << "get b" << " b = " << b << endl;
cout << "1 : a + b = " << a + b << endl;
}
void thread2()
{
cout << "thread2 is running" << endl;
lock(mx1, mx2);
lock_guard<mutex> guard1(mx1, adopt_lock);//adopt_lock自适应上锁,如果上过锁了就不会重复上锁
lock_guard<mutex> guard2(mx2, adopt_lock);
cout << "thread2's num is " << b << endl;
Sleep(1000);
cout << "get a" << " a = " << a << endl;
cout << "2 : b - a = " << b - a << endl;
}