如題,使用mutex互斥量和semaphore信號量實作多個生產者和一個消費者模型。本來是想只用semaphore信號量實作生產者消費者模型,但是發現在多個生產者和消費者中會出現消費者先消費的情況,要實作多個生產者和一個消費者模型必須要用互斥鎖來鎖定當前執行緒,但怎么在代碼中加入sem信號量來實作多個生產者和一個消費者的模型。
代碼如下:
#include <stdio.h>
#include <pthread.h>
#include<unistd.h>
pthread_mutex_t mutex;//互斥信號量
pthread_cond_t empty,full;//條件變數
int buffer[10];//生產者、消費者緩沖區
void *producer(void *p){
int i;
for(i=0; i<10; i++)
{
pthread_mutex_lock(&mutex); //互斥鎖,互斥使用緩沖區 ,以防止多個執行緒同時請求pthread_cond_wait()
while(buffer[i]!=0){ //用于判斷緩沖區
pthread_cond_wait(&empty, &mutex);//條件成立
}
printf("procucer produce %d\n",i);
usleep(1000*1000/2);
pthread_cond_signal(&full);//喚醒消費者 激活等待該條件的執行緒
pthread_mutex_unlock(&mutex);//釋放互斥鎖
}
pthread_exit(0);
}
void *consumer(void *p){
int i;
for(i=0; i<10; i++)
{
pthread_mutex_lock(&mutex);//互斥鎖,互斥使用緩沖區,以防止多個執行緒同時請求pthread_cond_wait()
while(buffer==0){
pthread_cond_wait(&full, &mutex);//
}
printf("consumer consume %d\n",i);
usleep(1000*1000/2);
buffer[i] = 0;//從緩沖區中取出資料
pthread_cond_signal(&empty);//喚醒生產者 激活等待該條件的執行緒
pthread_mutex_unlock(&mutex);//釋放互斥鎖
}
pthread_exit(0);
}
int main(){
pthread_t pid[3];
pthread_mutex_init(&mutex,0);//初始化函式
pthread_cond_init(&empty,0);
pthread_cond_init(&full,0);
pthread_create(&pid[0],NULL,producer,NULL);//創建執行緒
pthread_create(&pid[1],NULL,consumer,NULL);
pthread_create(&pid[2],NULL,producer,NULL);
for(int i=0;i<3;i++){
pthread_join(pid[i],0);//用來等待一個執行緒的結束,執行緒間同步的操作
}
pthread_cond_destroy(&empty);//銷毀條件變數
pthread_cond_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/20985.html
標籤:系統維護與使用區
