/**
* Created by fangruibin
* 测试死锁产生的场景
*/
#include <iostream>
#include <pthread.h>
#include <unistd.h>
//定义两把锁
pthread_mutex_t m_mutex1;
pthread_mutex_t m_mutex2;
int A = 0, B = 0;
//线程1
void* threadFunc1(void* p)
{
//printf("thread 1 running..\n");
pthread_mutex_lock(&m_mutex1);
A = 1;
printf("thread 1 write source A\n");
usleep(100);
pthread_mutex_lock(&m_mutex2);
B = 1;
printf("thread 1 write source B\n");
//解锁,实际上是跑不到这里的,因为前面已经死锁了
pthread_mutex_unlock(&m_mutex2);
pthread_mutex_unlock(&m_mutex1);
return NULL;
}
//线程2
void* threadFunc2(void* p)
{
//printf("thread 2 running..\n");
pthread_mutex_lock(&m_mutex2);
B = 1;
printf("thread 2 write source B\n");
usleep(100);
pthread_mutex_lock(&m_mutex1);
A = 1;
printf("thread 2 write source A\n");
//解锁,实际上是跑不到这里的,因为前面已经死锁了
pthread_mutex_unlock(&m_mutex1);
pthread_mutex_unlock(&m_mutex2);
return NULL;
}
int main()
{
//初始化锁
if (pthread_mutex_init(&m_mutex1, 0) != 0)
{
printf("init mutex 1 failed\n");
return -1;
}
if (pthread_mutex_init(&m_mutex2, 0) != 0)
{
printf("init mutex 2 failed\n");
return -1;
}
//初始化线程
pthread_t hThread1;
pthread_t hThread2;
if (pthread_create(&hThread1, NULL, &threadFunc1, NULL) != 0)
{
printf("create thread 1 failed\n");
return -1;
}
if (pthread_create(&hThread2, NULL, &threadFunc2, NULL) != 0)
{
printf("create thread 2 failed\n");
return -1;
}
while (1)
{
sleep(1);
}
pthread_mutex_destroy(&m_mutex1);
pthread_mutex_destroy(&m_mutex2);
return 0;
}
面试官要求用c++写一个死锁的程序。
目前想到两种简单的写法,一种是单线程对一个资源重复申请上锁;第二种是两个线程对两个资源申请上锁,形成环路。
实现一:单线程对一个资源重复申请上锁
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
using namespace std;
int data = 1;
mutex mt1,mt2;
void a2() {
data = data * data;
mt1.lock(); //第二次申请对mt1上锁,但是上不上去
cout<<data<<endl;
mt1.unlock();
}
void a1() {
mt1.lock(); //第一次对mt1上锁
data = data+1;
a2();
cout<<data<<endl;
mt1.unlock();
}
int main() {
thread t1(a1);
t1.join();
cout<<"main here"<<endl;
return 0;
}
实现二、两个线程对两个资源申请上锁,形成环路
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
using namespace std;
int data = 1;
mutex mt1,mt2;
void a2() {
mt2.lock();
sleep(1);
data = data * data;
mt1.lock(); //此时a1已经对mt1上锁,所以要等待
cout<<data<<endl;
mt1.unlock();
mt2.unlock();
}
void a1() {
mt1.lock();
sleep(1);
data = data+1;
mt2.lock(); //此时a2已经对mt2上锁,所以要等待
cout<<data<<endl;
mt2.unlock();
mt1.unlock();
}
int main() {
thread t2(a2);
thread t1(a1);
t1.join();
t2.join();
cout<<"main here"<<endl; //要t1线程、t2线程都执行完毕后才会执行
return 0;
}