由于互斥锁的使用不当,导致多个线程无法进行下一步的代码运行,也就是说竞争锁的两个线程互相锁住,导致整个进程无法往下运行。
举个例子:
两个锁,两个线程,两个线程运行的条件都是需要同时获得这两把锁,但是这两个线程一人获得了一把锁,又想去获得对方手里的那把锁,但是互相都不让出手里的锁,就会出现死锁的情况。
#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 *)¶m);if(ret == 0){printf("main:create t1 success\n");}ret = pthread_create(&t2, NULL, func2,(void *)¶m);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两个线程后就卡死了,不再往后运行了。当然在真正编写代码是不会出现以上这种比较弱智的情况,但是,当代码复杂程度升高,循环判断的不断嵌套,需要管理的锁增加,会容易出现这种情况,需要去避免。