2016-10-18 25 views
0

我使用pthread_cond_wait()和函數來創建一個多線程程序。它工作正常,如果條件正確,但條件不正確,它不工作,它不會忽略功能printinput(),它留在這裏,不運行繼續。你能幫我檢查這個錯誤嗎?pthread不工作使用pthread_cond_signal()和pthread_cond_wait()

我的代碼:

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

pthread_mutex_t mutex; 
pthread_cond_t cond; 

//Read input value 
void* readinput(void *arg) 
{ 
    pthread_mutex_lock(&mutex); 
     int a; 
     printf("Input:"); 
     scanf("%d",&a); 
     printf("Value: %d\n",a); 
     /* 
     if condition correct then "printinput" function 
     else ignore that function 
     */ 
     if (a>=2 && a<=8) 
     { 
      pthread_cond_signal(&cond); 
     } 
    pthread_mutex_unlock(&mutex); 
    pthread_exit((void *)a); 
} 

//print input value if condition correctly 
void* printinput(void *arg) 
{ 
    pthread_mutex_lock(&mutex); 
    //Block and wait for cond Singal 
     pthread_cond_wait(&cond,&mutex); 
     printf("Your value between 2 and 8 \n\n"); 
    pthread_mutex_unlock(&mutex); 
    pthread_exit(NULL); 
} 
int main() 
{ 
    pthread_mutex_init(&mutex, NULL); 
    pthread_cond_init(&cond, NULL); 
    pthread_t th1; 
    pthread_t th2; 
    while (1) 
    { 

     //Create pthread 
     pthread_create(&th1,NULL,&printinput,NULL); 
     pthread_create(&th2,NULL,&readinput,NULL); 

     //Wait pthread done 
     pthread_join(th1,NULL); 
     pthread_join(th2,NULL); 
     Sleep(1000); 
    } 
} 

結果:

Input:5 
Value: 5 
Your value between 2 and 8 
Input:10 Value: 10 

回答

0

pthread_cond_wait()掛起當前線程,直到相關的條件獲得信號。

對於輸入5第一個線程表示條件,因爲它是if (a >= 2 && a <= 8)塊的一部分。

對於輸入10,上面的程序段被跳過,所以條件從不發出信號。因此第二個線程永遠不會被喚醒並永久卡住。

此外,請注意有競爭條件,我真的很驚訝,該程序經常工作。在第一個線程鎖定互斥鎖的情況下,第二個線程在第一個線程函數完成之前不會進入互斥鎖部分,因此在調用等待條件之前發送條件。在這種情況下,第二個線程也會永久停留。

對於以您期望的方式工作的解決方案(即從第二個線程中的第一個線程消耗true/false),我建議實現一個隊列,第一個線程將發送輸出,第二個線程將其消耗。它也會解決比賽條件。有關實施,請參閱示例https://stackoverflow.com/a/4577987/4787126

相關問題