18.執行緒同步:條件變數cond—>生產者消費者模型
阿新 • • 發佈:2018-11-12
條件變數:[單生產者/單消費者]單鏈表的插入和刪除
typedef struct node{//宣告連結串列型別 int data; struct node* next; }LNode; LNode* head=NULL; //臨界資源:連結串列的頭節點 pthread_mutex_t mutex; pthread_cond_t cond; void* producer(void* arg){ while(1){ LNode* node=(LNode*)malloc(sizeof(LNode)); //建立新的節點node node->data=rand()%100; pthread_mutex_lock(&mutex); node->next=head; //將node採用頭插法插入連結串列 head=node; printf(" produce node=%d\n",node->data); pthread_mutex_unlock(&mutex); sleep(rand()%3); pthread_cond_signal(&cond); //插入node後,喚醒等待的執行緒去消費連結串列 } return NULL; } void* customer(void* arg){ while(1){ pthread_mutex_lock(&mutex); while(head==NULL){ //if(head==NULL) 如果連結串列為NULL,則一直阻塞 pthread_cond_wait(&cond,&mutex); } //採用頭刪法刪除節點 LNode* delNode=head; head=head->next; //delete head printf("delete node=%d\n",delNode->data); free(delNode); pthread_mutex_unlock(&mutex); sleep(rand()%3); } return NULL; } int main(){ pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_t tid1,tid2; pthread_create(&tid1,NULL,producer,NULL); pthread_create(&tid2,NULL,customer,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }