生产者负责生成,消费负责消耗。产品满的时候,停止生成,开始消费。空的时候停止消费,开始生产。消费和生成是不能见面(同时操控数据)
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<stdlib.h>
typedef struct data{
pthread_mutex_t mutex;
sem_t full;
sem_t empty;
int val[10];
}dataPro;
void* product(void *d){
sleep(5);
dataPro* data = (dataPro*)d;
while(1){
sem_wait(&data->empty);//为空的时候开始生产
pthread_mutex_lock(&data->mutex);
for(int i = 0; i < 10; i++){
data->val[i] = 1;
printf("生产者:count = %d,data = %d\n",i , data->val[i]);
}
sleep(5);
pthread_mutex_unlock(&data->mutex);
sem_post(&data->full);
}
}
void* consume(void *d){
sleep(5);
dataPro* data = (dataPro*)d;
while(1){
sem_wait(&data->full);//满了 就开始消费
pthread_mutex_lock(&data->mutex);
for(int i = 0; i < 10; i++){
data->val[i] = 0;
printf("消费者:count = %d,data = %d\n", i,data->val[i]);
}
sleep(5);
pthread_mutex_unlock(&data->mutex);
sem_post(&data->empty);
}
}
//数据 初始化
dataPro* initData(){
dataPro *data = (dataPro*)malloc(sizeof(data));
sem_init(&data->empty, 0, 1);
sem_init(&data->full, 0 ,0);
pthread_mutex_init(&data->mutex, NULL);
return data;
}
int main(){
dataPro *data= initData();
pthread_t pthreadWait,pthreadPost;
//开始2个线程,生产,消费
pthread_create(&pthreadWait, NULL, consume, data);
pthread_create(&pthreadPost, NULL, product, data);
//数据清理
sleep(50);
pthread_join(pthreadPost, NULL);
pthread_join(pthreadWait, NULL);
sem_destroy(&data->empty);
sem_destroy(&data->full);
free(data);
return 0;
}
结果:
网上有很多关于生产者消费原理的描述,这里就不做过多陈述了,只贴代码。
<a href="http://zh.wikipedia.org/wiki/%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E9%97%AE%E9%A2%98">wiki百科关于生产者,消费者描述</a>