經典生產者消費者程序。當前嘗試讓消費者等待隊列爲空。隊列是內存中的一個結構。我遇到了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);
}
我們可以看到初始化互斥鎖和條件變量的代碼嗎?放屁。 –
...放屁。那不是在隊列結構中初始化? –
你只需調用'malloc'。你認爲什麼初始化互斥和條件變量? –