Linux系统编程:使用mutex互斥锁和条件变量实现多个生成者和消费者模型
生活随笔
收集整理的這篇文章主要介紹了
Linux系统编程:使用mutex互斥锁和条件变量实现多个生成者和消费者模型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現代碼
如題,使用mutex互斥鎖和條件變量實現多個生成者和消費者模型。
直接上代碼,需要線程中的互斥鎖和條件變量的相關知識進行支撐。這里就不細說了呀,代碼中有一定的注釋。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <error.h> #include <sys/errno.h> #include <pthread.h> //產品 typedef struct Msg{struct Msg* next;int num; }Msg; pthread_mutex_t lock =PTHREAD_MUTEX_INITIALIZER; //靜態初始化mutex 互斥鎖,也可以使用pthread_mutex_init方法進出初始化 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化條件變量 Msg* head = NULL; //生產者 void* produce(void* arg) {Msg* msg = NULL;int i = (int)arg;//序號while(1){msg = (Msg*)malloc(sizeof(Msg));msg->num = rand()%1000;//添加到公共區域pthread_mutex_lock(&lock);msg->next = head;head = msg;pthread_mutex_unlock(&lock);printf("%dth ***producer***:%d\n",i,msg->num);pthread_cond_broadcast(&cond);sleep(rand()%3);}return NULL; } void* custome(void* arg) {Msg* msg = NULL;int i = (int)arg;//序號while(1){pthread_mutex_lock(&lock);//為什么 while而不是if ?當沒有產品時,多個消費者線程有可能同時阻塞在cond_wait。//當產品區有一個產品,被喚醒的一個消費者將產品消費,其他產品再次消費時,需要判斷產品區是否有產品while( head == NULL ){pthread_cond_wait(&cond,&lock);}//消費msg = head;head = msg->next;pthread_mutex_unlock(&lock);printf("%dth ###customer###:%d\n",i,msg->num);free(msg);sleep(rand()%3);}return NULL; } int main(int argc,char* argv[]) {srand((unsigned int)time(NULL));pthread_t pro[3],cus[5];int i;//3 個生產者線程for(i = 0 ; i <3; i++){pthread_create(&pro[i],NULL,produce,(void*)i);}//5 個消費者線程for( i = 0; i < 5; i++ ){pthread_create(&cus[i],NULL,custome,(void*)i);}pthread_mutex_destroy(&lock);//主線程回收線程for( i = 0; i < 3; i++ ){pthread_join(pro[i],NULL);}for( i = 0; i < 5; i++ ){pthread_join(cus[i],NULL);}return 0; }實現效果
總結
以上是生活随笔為你收集整理的Linux系统编程:使用mutex互斥锁和条件变量实现多个生成者和消费者模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CEF3—在网页加载前给js对象填值
- 下一篇: linux C 应用消息队列在两个进程间