2017-04-13 35 views
0

經典生產者消費者程序。當前嘗試讓消費者等待隊列爲空。隊列是內存中的一個結構。我遇到了pthread_cond_wait()函數的問題。我們不允許使用全局變量,因此我將pthread_cond和mutex存儲在隊列結構中的內存中。 pthread_cond_wait()將整數6返回到condWaitCheck,這表示發生以下任一情況。pthread_cond_wait()不等,返回int 6

[EINVAL] cond,mutex或abstime指定的值無效。

[EINVAL] 不同互斥併發調用pthread_cond_wait()或那麼pthread_cond_timedwait()在相同的條件變量操作均提供。

[EINVAL] 在調用時,互斥鎖並不屬於當前線程。

而我似乎無法弄清楚哪個是我的問題。

typedef struct queue { 
    int element[MAX_QUEUE_SIZE]; 
    int prod_id[MAX_QUEUE_SIZE]; 
    int head; 
    int tail; 
    int remaining_elements; 
    pthread_mutex_t myMutex; 
    pthread_cond_t condConsumer; 
    pthread_cond_t condProducer; 
} prod_cons_queue; 

void queue_initialize(prod_cons_queue *q){ 
    q->head = -1; 
    q->tail = -1; 
    q->remaining_elements=0; 
    pthread_cond_init (q->condConsumer,NULL); 
    pthread_cond_init (q->condProducer,NULL); 
    pthread_mutex_init (q->myMutex,NULL); 
} 

void *consumerFunc(void* prodID) { 
    int condWaitCheck; 

    pthread_mutex_lock (&(((prod_cons_queue *)prodID)->myMutex)); 

    if (((prod_cons_queue *)prodID)->remaining_elements == 0){ 
     cout << "waiting in consumer..." << endl; 
     pthread_cond_wait(&(((prod_cons_queue *)prodID)->condConsumer), &(((prod_cons_queue *)prodID)->myMutex)); 

     if (condWaitCheck!=0){ 
      cout << "There was an error on pthread_cond_wait:" << condWaitCheck << endl; 
     } 
    } 
    cout << "unlocking from consumer... " << endl; 
    pthread_mutex_unlock (&((prod_cons_queue *)prodID)->myMutex); 

    return NULL; 

} 

int main(){ 
    //Producer consumer queue initialized 
    prod_cons_queue *q = (prod_cons_queue*) malloc (sizeof(prod_cons_queue*)); 
    //q->head = 42; 

    //********************** CREATE CONSUMER ********************** 
    pthread_t consumer; 
    int conCheck; 
    conCheck = pthread_create(&consumer,NULL,&consumerFunc,(void*)q); //passing void pointer type variable q 

    if (conCheck!=0){ 
     cout << "Error:unable to create thread," << conCheck << endl; 
     //exit(-1); 
    } 
+0

我們可以看到初始化互斥鎖和條件變量的代碼嗎?放屁。 –

+0

...放屁。那不是在隊列結構中初始化? –

+0

你只需調用'malloc'。你認爲什麼初始化互斥和條件變量? –

回答

1

malloc函數只是分配內存。它不會使該內存包含有效的互斥鎖或條件變量。你需要初始化它們。 (或者,更好的是,使用new和現代C++線程構造。)

+0

謝謝大衛。我添加了我的初始化函數並添加了互斥鎖和cond inits(在我啓動我的隊列之前,我需要在main()中調用它)。 –

+1

'pthread_cond_init'接受'pthread_cond_t *',你傳遞一個'pthread_cond_t'。 –