使用互斥鎖的死鎖
在使用互斥鎖的多執行緒 Pthread 程式中會發生死鎖。讓我們看看如何發生。未鎖定的互斥鎖由 pthread_mutex_init() 函式初始化。
使用 pthread_mutex_lock() 和 pthread_mutex_unlock() 來獲取和釋放互斥鎖。如果一個執行緒嘗試獲取被鎖定的互斥鎖,則 pthread_mutex_lock() 呼叫的執行緒將被阻塞,直到互斥鎖的所有者呼叫 pthread_mutex_unlock()。
我們舉個例子,在下面的程式碼中建立了兩個互斥鎖 −
/* Create and initialize the mutex locks */ pthread mutex t mutex1; pthread mutex t mutex2; pthread mutex init(&mutex1,NULL); pthread mutex init(&mutex2,NULL);
接下來,建立了兩個執行緒(thread1 和 thread2),這兩個執行緒都可以訪問這兩個互斥鎖。Thread1 和 thread2 分別在函式 dosomework_1 和 dosomework_2 中執行,如下所示 −
/* thread1 runs in this function */ void *dosomework_1(void *param) { pthread mutex lock(&mutex1); pthread mutex lock(&mutex2); /** * Do some work */ pthread mutex unlock(& mutex2); pthread mutex unlock(& mutex2); pthread exit(0); } /* thread2 runs in this function */ void *dosomework_2(void *param) { pthread mutex lock(&mutex2); pthread mutex lock(&mutex1); /** * Do some work */ pthread mutex unlock(&mutex1); pthread mutex unlock(&mutex2); pthread exit(0); }
在這個示例中,thread1 嘗試按以下順序獲取互斥鎖
- mutex1,
- mutex2,
而 thread two 嘗試按以下順序獲取互斥鎖
- mutex2,
- mutex1,
如果 thread1 獲取 mutex1,而 thread2 獲取 mutex2,則可能會發生死鎖。即使可能會發生死鎖,如果 thread1 可以在 thread2 嘗試獲取鎖之前獲取和釋放 mutex1 和 mutex2 的互斥鎖,則不會發生這種情況。當然,CPU 排程程式會安排執行緒執行的順序。上述示例說明了處理死鎖所存在的問題:很難識別和測試只在某些排程情況下可能發生的死鎖。
廣告