[学习资料] 两个线程,两个互斥锁如何形成死锁?

[复制链接]
548|3
 楼主| 中国龙芯CDX 发表于 2023-12-27 08:57 | 显示全部楼层 |阅读模式
程序流程图如下:


程序流程图
如上图所示:

t0时刻,主线程创建子线程,并初始化互斥锁mutex1、mutex2;
t1时刻,主线程申请到了mutex1、子线程申请到了mutex2;
t2时刻,主线程和子线程都sleep 1秒钟,防止优先获得时间片的线程直接申请到了另外1个互斥锁,导致程序直接退出;
t3时刻,主线程和子线程都想获得对方手里的互斥锁,但是对方都来不及释放自己手里的锁;
t4时刻,主线程和子线双双进入休眠。
【注意】为了保证主线程和子线程都能够分别获得锁mutex1、mutex2,各自获得锁后一定要先sleep 1秒钟,否则创建完子线程后,主线程还有一定的时间片,主线程会申请到锁mutex2,无法形成死锁。


死锁

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

×
 楼主| 中国龙芯CDX 发表于 2023-12-27 08:58 | 显示全部楼层
源码如下


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <pthread.h>   

  5. unsigned int value1, value2, count;
  6. pthread_mutex_t  mutex1,mutex2;
  7. void *function(void *arg);


  8. void  *function(void *arg)
  9. {
  10. pthread_mutex_lock(&mutex2);
  11. printf("new thread get mutex2\n");
  12. sleep(1);
  13. pthread_mutex_lock(&mutex1);
  14. printf("new thread get mutex1\n");


  15. pthread_mutex_unlock(&mutex1);
  16. printf("new thread release mutex1\n");
  17. pthread_mutex_unlock(&mutex2);
  18. printf("new thread release mutex2\n");
  19.     return  NULL;
  20. }  

  21. int main(int argc,  char *argv[])
  22. {
  23. pthread_t  a_thread;
  24.          
  25. if (pthread_mutex_init(&mutex1, NULL) < 0)
  26. {
  27.   perror("fail to mutex_init");
  28.   exit(-1);
  29. }
  30.   if (pthread_mutex_init(&mutex2, NULL) < 0)
  31. {
  32.   perror("fail to mutex_init");
  33.   exit(-1);
  34. }              
  35. if (pthread_create(&a_thread, NULL, function, NULL) < 0)
  36. {   
  37.   perror("fail to pthread_create");     
  38.   exit(-1);
  39. }
  40.     while ( 1 )
  41.     {
  42.         pthread_mutex_lock(&mutex1);
  43.   printf("main thread get mutex1\n");
  44.   sleep(1);
  45.         pthread_mutex_lock(&mutex2);  
  46.   printf("main thread get mutex2\n");
  47.         pthread_mutex_unlock(&mutex2);
  48.   printf("main thread release mutex2\n");
  49.         pthread_mutex_unlock(&mutex1);
  50.   printf("main thread release mutex1\n");
  51.     }
  52.     return 0;
  53. }   

自己的灌饼 发表于 2023-12-27 09:14 | 显示全部楼层
多线程的任务管理吗?还是需要依赖于操作系统?
AdaMaYun 发表于 2023-12-28 17:53 | 显示全部楼层
楼主这个讲解的很详细,需要进一步学习
您需要登录后才可以回帖 登录 | 注册

本版积分规则

339

主题

2677

帖子

4

粉丝
快速回复 在线客服 返回列表 返回顶部