2017-08-11 45 views
1

當我在尋找主題時,我從here找到了代碼。正如你所看到的,這兩個函數的線程使用相同的mutex。那麼,即使先前的線程擁有互斥鎖,另一個線程如何發出信號或捕獲信號並繼續其功能?如何/爲什麼沒有死鎖?這有點令人困惑。Pthread條件變量並且沒有死鎖

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

pthread_mutex_t count_mutex  = PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; 

void *functionCount1(); 
void *functionCount2(); 
int count = 0; 
#define COUNT_DONE 10 
#define COUNT_HALT1 3 
#define COUNT_HALT2 6 

main() 
{ 
    pthread_t thread1, thread2; 

    pthread_create(&thread1, NULL, &functionCount1, NULL); 
    pthread_create(&thread2, NULL, &functionCount2, NULL); 

    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 

    printf("Final count: %d\n",count); 

    exit(EXIT_SUCCESS); 
} 

// Write numbers 1-3 and 8-10 as permitted by functionCount2() 

void *functionCount1() 
{ 
    for(;;) 
    { 
     // Lock mutex and then wait for signal to relase mutex 
     pthread_mutex_lock(&count_mutex);  //  <---- Same mutex 

     // Wait while functionCount2() operates on count 
     // mutex unlocked if condition varialbe in functionCount2() signaled. 
     pthread_cond_wait(&condition_var, &count_mutex); 
     count++; 
     printf("Counter value functionCount1: %d\n",count); 

     pthread_mutex_unlock(&count_mutex); 

     if(count >= COUNT_DONE) return(NULL); 
    } 
} 

// Write numbers 4-7 

void *functionCount2() 
{ 
    for(;;) 
    { 
     pthread_mutex_lock(&count_mutex); //  <---- Same mutex 

     if(count < COUNT_HALT1 || count > COUNT_HALT2) 
     { 
      // Condition of if statement has been met. 
      // Signal to free waiting thread by freeing the mutex. 
      // Note: functionCount1() is now permitted to modify "count". 
      pthread_cond_signal(&condition_var); 
     } 
     else 
     { 
      count++; 
      printf("Counter value functionCount2: %d\n",count); 
     } 

     pthread_mutex_unlock(&count_mutex); 

     if(count >= COUNT_DONE) return(NULL); 
    } 

} 

回答

0

如果一個線程擁有 鎖,那麼其他人能不能另外一個釋放之前獲取它。
現在,如果線程A首先獲取了鎖,它將阻止線程B在關鍵部分從 前進,直到鎖釋放。


爲什麼沒有一個僵局?


this

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); 

該功能自動釋放互斥和導致調用線程阻塞條件變量COND;

線程A將釋放鎖定,當它到達cond_wait並且線程B可以前進併發信號通知條件變量時。

+0

你不明白我問什麼。我要求兩個人使用相同的互斥鎖,如果其中一個擁有授權,另一個必須等​​待進入其互斥區。如果是這樣,在functionCount1中,由thread1和pthread_cond_wait擁有的互斥量正在進行中。在這一行它是否等待functionCount2(線程2)?或者如果線程2擁有互斥量,線程1如何遞增計數?即使互斥鎖已經被thread2所有? – concurrencyboy

+0

但它像一個沒有任何僵局的魅力? – concurrencyboy

+0

@concurrencyboy立即嘗試。令我困惑的是,事實上,線程A一旦運行'cond_wait'就會釋放鎖。否則它會在線程A首先獲取鎖的情況下發生死鎖。 –