Linux系统编程:使用semaphore信号量和mutex互斥量实现多个生产者和消费者模型
生活随笔
收集整理的這篇文章主要介紹了
Linux系统编程:使用semaphore信号量和mutex互斥量实现多个生产者和消费者模型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼實現
如題,使用semaphore信號量和mutex互斥量實現多個生產者和消費者模型。本來是想只用信號量實現生產者消費者模型的,但是發現 只能在一個生產者和一個消費者之間,要在多個生產者和消費者模型必須和mutex互斥鎖搭配使用才行,sem信號量只是控制并發數的。采用數組模擬產品區,代碼中有一定的注釋。需要Linux下線程相關知識進行支撐,這里不細說,直接看實現代碼。
#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> #include <semaphore.h> #define NUM 10 //產品區容量 int queue[NUM] = {0};//數組模擬產品區,生產者消費者運行模擬環形隊列進行生產和消費 sem_t producer,customer;//信號量 int pro_i = 0;//生產者線程 訪問下標 int cus_i = 0;//消費者線程 訪問下標 pthread_mutex_t pro_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t cus_lock = PTHREAD_MUTEX_INITIALIZER;//生產者 void* produce(void* arg) {int tmp;//生產從下標 0 -> Nwhile(1){sem_wait(&producer); //producer-- ,直到為0 產品區被填滿 進行阻塞//并行的生產者線程生成產品pthread_mutex_lock(&pro_lock); tmp = queue[pro_i] = rand()%1000 ;pro_i = (pro_i+1)%NUM;pthread_mutex_unlock(&pro_lock);printf("%dth ###producer###:%d\n",(int)arg,tmp);sem_post(&customer);//customer++sleep(rand()%2);}return NULL; } //消費者 void* custome(void* arg) {int tmp;//消費從下標0 -> N while(1){sem_wait(&customer); // customer-- ,直到為0 產品區為空 進行阻塞//并行的消費者線程訪問消費產品pthread_mutex_lock(&cus_lock);tmp = queue[cus_i];queue[cus_i] = 0 ;cus_i = (cus_i+1)%NUM;pthread_mutex_unlock(&cus_lock);printf("%dth ***customer***:%d\n",(int)arg,tmp);sem_post(&producer);//producer++ sleep(rand()%2);}return NULL; } //使用信號量 實現生產者消費者模型 int main(int argc,char* argv[]) {srand((unsigned int)time(NULL));//設置線程分離pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);pthread_t pro[3],cus[5]; int i;//初始化信號量 起初產品區為空sem_init(&producer,0,NUM);//生產者 起初信號量為 NUM 產品區為空生產產品,當信號量為0 也就是產品滿 阻塞等待消費者消費產品sem_init(&customer,0,0); //消費者 起初信號量為 0 阻塞等待生產者生產產品for( i= 0; i< 3;i++ ){pthread_create(&pro[i],&attr,produce,(void*)i);}for( i= 0; i< 5;i++ ){pthread_create(&cus[i],&attr,custome,(void*)i);}//銷毀 信號量sem_destroy(&producer);sem_destroy(&customer);//銷毀 鎖pthread_mutex_destroy(&pro_lock);pthread_mutex_destroy(&cus_lock);//主線程退出pthread_exit(NULL);return 0; }實現效果
總結
以上是生活随笔為你收集整理的Linux系统编程:使用semaphore信号量和mutex互斥量实现多个生产者和消费者模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ROS(kinetic)报错:CMake
- 下一篇: 属性文法和语法制导翻译