在Linux系统编程中,可能会遇到死锁问题,那什么情况下会产生死锁呢?
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,
// void *(*start_rtn)(void*),void *arg);
int sharg = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void *t1_func(void *arg)
{
pthread_mutex_lock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("this print from t1:sharg=%d\n",sharg);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex2);
pthread_exit(0);
}
void *t2_func(void *arg)
{
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex);
sharg++;
printf("this print from t2\n");
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_mutex_init(&mutex2,NULL);
pthread_create(&t1,NULL,&t1_func,NULL);
pthread_create(&t2,NULL,&t2_func,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex2);
return 0;
}
在这段代码中:
线程t1和线程t2分别对mutex和mutex2进行加锁
过了一秒后分别对mutex2和mutex也进行加锁
此时,对t2来说,因为一秒前mutex被t1加锁,所以t2阻塞
同理,t1也会产生阻塞
并且,这两个互斥量无法得到释放,导致程序阻塞
也就是死锁现象