我正在創建一個使用雙緩衝的線程化應用程序,我試圖避免潛在的死鎖。主要思想是交換緩衝區線程鎖定寫入和讀取線程。然而,交換緩衝區線程很快,所以鎖不會長時間保持鎖定狀態。寫入和讀取線程較慢,但高效共享時間片(目標),因爲它們鎖定在不同的互斥鎖上。我的問題是這種設計有潛在的僵局嗎?C雙緩衝區實現死鎖?
- 3線程...線程A,線程B,和C.螺紋
- 2互斥...前互斥和後退的互斥。
- 線程A填充後緩衝器
- 線程B交換緩衝器。
- 線程C使用前端緩衝區。
- 線程A需要theBackMutex,填充後緩衝,釋放theBackMutex。
- 線程C使用FrontMutex,使用前臺緩衝區,釋放FrontMutex。
- 線程B需要theBackMutex,theFrontMutex,切換緩衝區,釋放theBackMutex,釋放theFront互斥
void *fill_back_buffer() {
while(1) {
if (0 != pthread_mutex_lock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//should we get new data for back buffer?
pthread_cond_wait(&theBackBufferRefresh, &theBackMutex);
//fill back buffer
if (0 != pthread_mutex_unlock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//hey we done filling the back buffer!
pthread_cond_signal(&theBackBufferFull);
}
}
void *swap_buffers() {
while(1) {
if (0 != pthread_mutex_lock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
if (0 != pthread_mutex_lock(&theFrontkMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//do we have new data in the back buffer?
pthread_cond_wait(&theBackBufferFull, &theBackMutex);
//swap buffers
char* tmp;
tmp = theBufferAPtr;
theBufferAPtr = theBufferBPtr;
theBufferBPtr = tmp;
if (0 != pthread_mutex_unlock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
if (0 != pthread_mutex_unlock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//hey please get more data!
pthread_cond_signal(&theBackBufferRefresh);
//hey you can use front buffer now!
pthread_cond_signal(&theBufferSwapped);
}
}
int main(int argc, char *argv[]) {
//initial fill of the back buffer
pthread_cond_signal(&theBackBufferRefresh);
while(1) {
if (0 != pthread_mutex_lock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_wait(&theBufferSwapped, &theFrontMutex);
//use the front buffer and do stuff with it
if (0 != pthread_mutex_unlock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
}
}
如果你不能工作,我們自己然後建立一個Petri網模型,並檢查它的方式。 – 2011-03-15 20:17:45
我會檢查一下,我以前從未使用過Petri網模型。謝謝。 – 2011-03-15 20:27:36
一旦你建立了你的模型,你可以將它導入到一個工具,並讓工具找到你的死鎖。漂亮的東西! – 2011-03-15 20:29:22