什么情况造成互斥锁死锁

编程入门 行业动态 更新时间:2024-10-22 16:19:59

什么情况造成互斥锁<a href=https://www.elefans.com/category/jswz/34/1769948.html style=死锁"/>

什么情况造成互斥锁死锁

由于互斥锁的使用不当,导致多个线程无法进行下一步的代码运行,也就是说竞争锁的两个线程互相锁住,导致整个进程无法往下运行。

举个例子:

两个锁,两个线程,两个线程运行的条件都是需要同时获得这两把锁,但是这两个线程一人获得了一把锁,又想去获得对方手里的那把锁,但是互相都不让出手里的锁,就会出现死锁的情况。

#include <stdio.h>
#include <pthread.h>pthread_mutex_t mutex1;
pthread_mutex_t mutex2;void *func1(void *arg)
{int i;pthread_mutex_lock(&mutex1);sleep(1);pthread_mutex_lock(&mutex2);for(i=0;i<3;i++){printf("t1:%ld thread is create\n",(unsigned long)pthread_self());printf("t1:param is %d\n",*((int *)arg));sleep(1);}pthread_mutex_unlock(&mutex1);pthread_mutex_unlock(&mutex2);}void *func2(void *arg)
{pthread_mutex_lock(&mutex2);sleep(1);pthread_mutex_lock(&mutex1);printf("t2:%ld thread is create\n",(unsigned long)pthread_self());printf("t2:param is %d\n",*((int *)arg));pthread_mutex_unlock(&mutex1);pthread_mutex_unlock(&mutex2);
}int main()
{int ret;int param = 100;pthread_t t1;pthread_t t2;pthread_mutex_init(&mutex1,NULL);pthread_mutex_init(&mutex2,NULL);ret = pthread_create(&t1, NULL, func1,(void *)&param);if(ret == 0){printf("main:create t1 success\n");}ret = pthread_create(&t2, NULL, func2,(void *)&param);if(ret == 0){printf("main:create t2 success\n");}printf("main:%ld\n",(unsigned long)pthread_self());pthread_join(t1,NULL);pthread_join(t2,NULL);pthread_mutex_destroy(&mutex1);pthread_mutex_destroy(&mutex2);return 0;
}

可以看到main函数创建了t1、t2两个线程后就卡死了,不再往后运行了。当然在真正编写代码是不会出现以上这种比较弱智的情况,但是,当代码复杂程度升高,循环判断的不断嵌套,需要管理的锁增加,会容易出现这种情况,需要去避免。

更多推荐

什么情况造成互斥锁死锁

本文发布于:2023-11-16 11:08:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620148.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:死锁   情况   互斥

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!