2016-07-26 53 views
1

我正在閱讀AS TANENBAUM的Modern Operation Systems一書,它給出了一個解釋條件變量的例子,如下所示。它看起來有一個僵局,不知道我想念什麼。互斥體中的死鎖,條件變量代碼?

讓我們假設消費者線程首先啓動。 後面緊接着the_mutex被鎖定,消費者線程被阻塞等待條件變量,condc

如果生產此時運行,the_mutex仍然會被鎖定,因爲消費者永遠不會釋放它。所以製片人也將被封鎖。

這看起來對我來說是一本教科書上的死鎖問題。我在這裏錯過了什麼嗎? THX

#include <stdio.h> 
#include <pthread.h> 

#define MAX 10000000000   /* Numbers to produce */ 
pthread_mutex_t the_mutex; 
pthread_cond_t condc, condp; 
int buffer = 0; 


void* consumer(void *ptr) { 
    int i; 

    for (i = 1; i <= MAX; i++) { 
    pthread_mutex_lock(&the_mutex); /* lock mutex */ 

    /*thread is blocked waiting for condc */ 
    while (buffer == 0) pthread_cond_wait(&condc, &the_mutex); 
    buffer = 0; 
    pthread_cond_signal(&condp);  
    pthread_mutex_unlock(&the_mutex); 
    } 
    pthread_exit(0); 
} 

void* producer(void *ptr) { 
    int i; 

    for (i = 1; i <= MAX; i++) { 
    pthread_mutex_lock(&the_mutex); /* Lock mutex */ 

    while (buffer != 0) pthread_cond_wait(&condp, &the_mutex); 
    buffer = i; 
    pthread_cond_signal(&condc);  
    pthread_mutex_unlock(&the_mutex); 
    } 
    pthread_exit(0); 
} 

int main(int argc, char **argv) { 
    pthread_t pro, con; 

    //Simplified main function, ignores init and destroy for simplicity 
    // Create the threads 
    pthread_create(&con, NULL, consumer, NULL); 
    pthread_create(&pro, NULL, producer, NULL); 
} 

回答

3

當你等待條件變量,關聯的互斥鎖被釋放等待的時間(這就是爲什麼你通過互斥調用pthread_cond_wait)。

當pthread_cond_wait返回時,互斥鎖總是被再次鎖定。

牢記這一點,您可以按照示例的邏輯。