C++语言模拟死锁
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
// 创建两个互斥锁
pthread_mutex_t mutex_A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_B = PTHREAD_MUTEX_INITIALIZER;
void* threadA_proc(void* data)
{
// 线程A获得资源A之前先进行加锁,等待1s,再以同样的方式获取资源B
cout << "thread A waiting get ResourceA" << endl;
pthread_mutex_lock(&mutex_A);
cout << "thread A get ResourceA" << endl;
sleep(1);
cout << "thread A waiting get ResourceB" << endl;
pthread_mutex_lock(&mutex_B);
cout << "thread A get ResourceB" << endl;
// 解锁
pthread_mutex_unlock(&mutex_B);
pthread_mutex_unlock(&mutex_A);
return (void*) 0;
}
void* threadB_proc(void* data)
{
// 线程B获得资源B之前先进行加锁,等待1s,再以同样的方式获取资源A
cout << "thread B waiting get ResourceB" << endl;
pthread_mutex_lock(&mutex_B);
cout << "thread B get ResourceB" << endl;
sleep(1);
cout << "thread B waiting get ResourceA" << endl;
pthread_mutex_lock(&mutex_A);
cout << "thread B get ResourceA" << endl;
// 解锁
pthread_mutex_unlock(&mutex_A);
pthread_mutex_unlock(&mutex_B);
return (void*) 0;
}
int main()
{
// 声明两个线程
pthread_t tidA, tidB;
pthread_create(&tidA, NULL, threadA_proc, NULL);
pthread_create(&tidB, NULL, threadB_proc, NULL);
// 等待子线程退出并回收其资源
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
cout << "exit" << endl;
return 0;
}
查看结果:
线程A在等待互斥锁mutex_B释放资源,线程B在等待互斥锁mutex_A释放资源,双方都在等待对方资源的释放,即产生死锁
避免死锁的发生
破坏产生死锁的四个必要条件
- 互斥条件
- 持有并等待条件
- 不可剥夺条件
- 环路等待条件
只需要破坏其中一个条件即可,最常见的就是使用资源有序分配法,破坏环路等待条件。
线程A、B获取两个互斥锁的顺序相同,即可,代码如下:
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
// 创建两个互斥锁
pthread_mutex_t mutex_A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_B = PTHREAD_MUTEX_INITIALIZER;
void* threadA_proc(void* data)
{
// 线程A获得资源A之前先进行加锁,等待1s,再以同样的方式获取资源B
cout << "thread A waiting get ResourceA" << endl;
pthread_mutex_lock(&mutex_A);
cout << "thread A get ResourceA" << endl;
sleep(1);
cout << "thread A waiting get ResourceB" << endl;
pthread_mutex_lock(&mutex_B);
cout << "thread A get ResourceB" << endl;
// 解锁
pthread_mutex_unlock(&mutex_B);
pthread_mutex_unlock(&mutex_A);
return (void*) 0;
}
void* threadB_proc(void* data)
{
cout << "thread B waiting get ResourceA" << endl;
pthread_mutex_lock(&mutex_A);
cout << "thread B get ResourceA" << endl;
sleep(1);
cout << "thread B waiting get ResourceB" << endl;
pthread_mutex_lock(&mutex_B);
cout << "thread B get ResourceB" << endl;
// 解锁
pthread_mutex_unlock(&mutex_B);
pthread_mutex_unlock(&mutex_A);
return (void*) 0;
}
int main()
{
// 声明两个线程
pthread_t tidA, tidB;
pthread_create(&tidA, NULL, threadA_proc, NULL);
pthread_create(&tidB, NULL, threadB_proc, NULL);
// 等待子线程退出并回收其资源
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
cout << "exit" << endl;
return 0;
}