互斥量和條件變數實現生產者消費者模型
阿新 • • 發佈:2019-01-29
/*producer and constmer*/ #include<stdio.h> #include<pthread.h> #include<string.h> #include<stdlib.h> pthread_mutex_t mutex; pthread_cond_t cond;// int good = 0; void *customer(void *argv)//消費者程式碼 { while(1) { pthread_mutex_lock(&mutex); if(good == 0) { pthread_cond_wait(&cond,&mutex);//當產品為0的時候,阻塞在條件變數,並釋放自己的互斥鎖。解除阻塞後會去獲取該互斥鎖 } good--; printf("customer:%d\n",good); pthread_mutex_unlock(&mutex);//消費完成釋放互斥鎖 sleep(rand()%3);//實現隨機消費 } return NULL; } void *producer(void *argv) { while(1) { pthread_mutex_lock(&mutex);//獲取互斥鎖進行生產 good++; printf("producer:%d\n",good); pthread_mutex_unlock(&mutex);//生產完成釋放該鎖 if(good == 1) pthread_cond_signal(&cond);//產品==1的時候釋放阻塞在產品為0的執行緒,通知其開始消費 sleep(rand()%3); } return NULL; } void main() { pthread_t pt1,pt2; pthread_mutex_init(&mutex,NULL);//初始化互斥鎖 pthread_cond_init(&cond,NULL);//初始化條件變數
pthread_create(&pt1,NULL,customer,NULL);//建立消費者執行緒
pthread_create(&pt2,NULL,producer,NULL);//建立生產者執行緒
pthread_join(pt1,NULL);//阻塞等待結束
pthread_join(pt2,NULL);
pthread_mutex_destroy(&mutex);//銷燬對應的鎖
pthread_cond_destroy(&cond);//銷燬條件變數
}