粉丝的提问,必须安排。
两个线程,两个互斥锁如何形成死锁?
程序流程图如下:
程序流程图
如上图所示:
- t0时刻,主线程创建子线程,并初始化互斥锁mutex1、mutex2;
- t1时刻,主线程申请到了mutex1、子线程申请到了mutex2;
- t2时刻,主线程和子线程都sleep 1秒钟,防止优先获得时间片的线程直接申请到了另外1个互斥锁,导致程序直接退出;
- t3时刻,主线程和子线程都想获得对方手里的互斥锁,但是对方都来不及释放自己手里的锁;
- t4时刻,主线程和子线双双进入休眠。
【注意】为了保证主线程和子线程都能够分别获得锁mutex1、mutex2,各自获得锁后一定要先sleep 1秒钟,否则创建完子线程后,主线程还有一定的时间片,主线程会申请到锁mutex2,无法形成死锁。
死锁
源码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
unsigned int value1, value2, count;
pthread_mutex_t mutex1,mutex2;
void *function(void *arg);
void *function(void *arg)
{
pthread_mutex_lock(&mutex2);
printf("new thread get mutex2\n");
sleep(1);
pthread_mutex_lock(&mutex1);
printf("new thread get mutex1\n");
pthread_mutex_unlock(&mutex1);
printf("new thread release mutex1\n");
pthread_mutex_unlock(&mutex2);
printf("new thread release mutex2\n");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t a_thread;
if (pthread_mutex_init(&mutex1, NULL) < 0)
{
perror("fail to mutex_init");
exit(-1);
}
if (pthread_mutex_init(&mutex2, NULL) < 0)
{
perror("fail to mutex_init");
exit(-1);
}
if (pthread_create(&a_thread, NULL, function, NULL) < 0)
{
perror("fail to pthread_create");
exit(-1);
}
while ( 1 )
{
pthread_mutex_lock(&mutex1);
printf("main thread get mutex1\n");
sleep(1);
pthread_mutex_lock(&mutex2);
printf("main thread get mutex2\n");
pthread_mutex_unlock(&mutex2);
printf("main thread release mutex2\n");
pthread_mutex_unlock(&mutex1);
printf("main thread release mutex1\n");
}
return 0;
}
编译运行
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
编译运行
从执行结果可以判断,主线程和子线程分别获得了互斥锁mutex1、mutex2,sleep 1秒后,他们都想再分别申请mutex2、mutex1,而双方都不想释放自己手中的锁,锁已形成了死锁,程序就一直处于休眠状态。
查看下该进程的线程
查看进程ID,为4204
查看该进程创建的线程id:4204、4205。
本文转载自微信公众号「一口Linux」,可以通过以下二维码关注。转载本文请联系一口Linux公众号。