死锁的产生:有一个公共区的玩具,A和B想玩,但是A先得到了玩具,A玩完玩具之后又去干别的事情,但是并没有把玩具还回去,此时B就玩不到了玩具,在无限期的等待。
如下图所示:
线程1把num资源给占用,线程2一直没办法获得num,线程2用于卡住了,与此同时,主线程的合流无法执行
第二中情况:
如果有一套玩具:比如鼓和敲鼓的锤子,A获得了鼓,B获得了锤,但是他们俩都不想放弃自己手里的玩具。A和B都永远玩不了敲鼓,在无限期等待。这也是一种死锁的情况。
如下图所示:
注意:这里的资源a和b各对应一把锁。
代码如下:
#include<iostream>
#include<thread>
#include<mutex>
#include<windows.h>
using namespace std;
void thread1();
void thread2();
mutex mx1;//鼓的锁
mutex mx2;//鼓槌的锁
int a;
int b;
int main(void)
{
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
return 0;
}
void thread1()
{
cout << "thread1 is running" << endl;
lock_guard<mutex> guard1(mx1);
cout << "thread1's num is " << a << endl;//拿到了鼓
Sleep(1000);//过了1秒反应过来还需要鼓槌
lock_guard<mutex> guard2(mx2);
cout << "get b" << " b = " << b << endl;
cout << "1 : a + b = " << a + b << endl;
}
void thread2()
{
cout << "thread2 is running" << endl;
lock_guard<mutex> guard2(mx2);//拿到了鼓槌
cout << "thread2's num is " << b << endl;
Sleep(1000);//过了1秒反应过来还需要鼓槌
lock_guard<mutex> guard1(mx1);
cout << "get a" << " a = " << a << endl;
cout << "2 : a + b = " << a + b << endl;
}