2015-11-15 19 views
0

那麼,下面的代碼爲兩個線程。我在互斥體上遇到了一些問題。 創建線程T1之後,它會調用add_queue()。然後它會發信號通知線t2在其關鍵部分工作。但是,該程序不運行線程t2。 線程t1運行並在其關鍵部分完成其工作。然後,我鎖定了線程t2的互斥鎖。但是,該方案被卡在管線29並行線程以及訪問所述臨界區

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

static int pending_requests =0; 
static pthread_mutex_t prmutex = PTHREAD_MUTEX_INITIALIZER; 
static pthread_cond_t prcondition = PTHREAD_COND_INITIALIZER; 

static int critical = 0; 

int get_number_requests(void) 
{ 
    return pending_requests; 
} 

void add_queue() 
{ 
    pthread_mutex_lock(&prmutex); 
    pending_requests++; 
    critical++;  
    pthread_mutex_unlock(&prmutex); 
    printf("xxxx\n"); 
    printf("critical=%d\n",critical); 

} 

void remove_from_queue() 
{ 
    pthread_mutex_lock(&prmutex); 
    pending_requests--; 
    printf("BBBBcritical=%d\n",critical); 
    critical--; 
    printf("BBBcritical=%d\n",critical); 

    pthread_mutex_unlock(&prmutex); 

} 

void *get_request() 
{ 
    add_queue(); 
    if (get_number_requests() != 0) 
    {  
     printf("I have a element in the queue. Signalling to processor thread..\n"); 
     pthread_cond_signal(&prcondition); 
    } 
    pthread_exit(0); 
} 

void *processor() 
{ 
    while(get_number_requests() == 0) 
    { 
     printf("BBB This is a processor thread, I am waiting..\n"); 
     pthread_cond_wait(&prcondition,&prmutex); 
    } 
    while(get_number_requests() !=0) 
    { 
     printf("aaaa\n"); 
     remove_from_queue(); 
     pthread_cond_signal(&prcondition); 
    } 

    pthread_exit(0); 
} 


int main() 
{ 
    pthread_t t1,t2; 
    printf("critical=%d\n",critical); 
    pthread_create(&t1,NULL,get_request,NULL); 
    pthread_create(&t2,NULL,processor,NULL); 
    printf("critical=%d\n",critical); 

    pthread_join(t1,NULL); 
    pthread_join(t2,NULL); 
} 

回答

1

您使用的pthread_cond_wait是錯誤的許多方面。該man pagepthread_cond_wait仔細閱讀將幫助您瞭解如何正確使用它。

  1. 在致電pthread_cond_wait之前,必須鎖定互斥鎖。從手冊:

    它們將被調用由調用線程鎖定的互斥鎖或 未定義的行爲結果。

    也就是說,在致電pthread_cond_wait之前,您需要致電pthread_mutex_lock

  2. pthread_cond_wait收益將有互斥鎖定。從手冊中:

    成功返回後,互斥鎖應該被鎖定並且應該由調用線程擁有。

    因此,試圖在remove_from_queue中再次鎖定它是錯誤的。由於該互斥鎖已經鎖定,該pthread_mutex_lock呼叫remove_from_queue將阻止無限期您發現(即線程死鎖本身)。

+0

謝謝,我會看到。 – rathore