Linux 死鎖例子
阿新 • • 發佈:2019-01-06
死鎖是在編寫多執行緒併發時候所需要考慮的問題,在多執行緒軟體使用多個互斥鎖來保護共享資源時,如果設計不合理會出現多個鎖相互巢狀並且都在等待彼此的鎖被釋放,這樣就會出現死鎖現象,讓系統掛起一直相互等待下去。下面給個例子說明這一現象:
/* 標頭檔案 */ #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); }