死锁产生实例,两个线程两个互斥锁,每个线程占有一个互斥锁,同时想获得另一个互斥锁则会产生死锁。
解决方案:
1.一次占有全部资源
2.每个线程占有锁的顺序是一致的。比如都是同时占有A,然后占有B锁。
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pthread.h> #include <signal.h> pthread_mutex_t mutex_one,mutex_two; pthread_mutex_t mutex; pthread_cond_t cond; void *thread_routine_one(void *arg) { pthread_cond_wait(&cond,&mutex);//确保two线程先运行 printf("thread_routine_one: lock mutex_one!\n"); pthread_mutex_lock(&mutex_one); printf("thread_routine_one: lock mutex_two!\n"); pthread_mutex_lock(&mutex_two);//获取two锁,这个要等待two线程对two锁的释放 sleep(1); printf("thread_routine_one: unlock mutex_two!\n"); pthread_mutex_unlock(&mutex_two); printf("thread_routine_one: unlock mutex_one!\n"); pthread_mutex_unlock(&mutex_one); return NULL; } void *thread_routine_two(void *arg) { printf("thread_routine_two: lock mutex_two!\n"); pthread_mutex_lock(&mutex_two);//获取two锁 pthread_cond_signal(&cond);//让one线程运行 sleep(1);//休眠,让one可以先运行获取one锁 printf("thread_routine_two: lock mutex_one!\n"); pthread_mutex_lock(&mutex_one);//获取one锁,这个同样必须等待one线程多one锁的释放 /**这时出现死锁现象了,在two线程要等待one线程对one锁的释放,同时two锁没有释放 * * 然而在one线程需要等待two线程对two锁的释放,然后才会对one锁的释放!出现相互等待的过程**/ printf("thread_routine_two: unlock mutex_one!\n"); pthread_mutex_unlock(&mutex_one); printf("thread_routine_two: unlock mutex_two!\n"); pthread_mutex_unlock(&mutex_two); return NULL; } void main() { pthread_t pthread_one,pthread_two; pthread_mutex_init(&mutex_one,NULL); pthread_mutex_init(&mutex_two,NULL); pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_create(&pthread_one,NULL,thread_routine_one,NULL); pthread_create(&pthread_two,NULL,thread_routine_two,NULL); while(1) sleep(1); }