概念简介
缓冲区:存放生产者产生的数据,消费者提取数据。
生产者:产生数据。
消费者:消耗数据。
生产与消费关系:当缓冲区达到最高预值,停止生产加快消耗,反之,则加快生产,停止
消耗。
demo:
1.定义字符串数组(大小20)作为缓冲区,字符#为货物。
2.定义线程t1为生产者,t2为消费者,t3发送信号。
3.数组大小为15,线程t1停止,数组为0,t2停止。
代码示例:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
char goods[20] = {'\0'};
pthread_mutex_t signal;
pthread_mutex_t mutex;
pthread_cond_t cond1;
pthread_cond_t cond2;
int goods_count(char goods[])
{
int i;
int num = 0;
for(i = 0;i < 20;i++)
{
if(goods[i] == '#')
{
num++;
}
}
return num;
}
void goods_adjust(char goods[])
{
int i;
if(goods_count(goods) > 0)
{
while(goods[0] == '\0')
{
for(i = 0;i < 18;i++)
{
goods[i] = goods[i+1];
}
}
goods[19] = '\0';
}
}
void consumer(char goods[],int num)
{
int i;
int output;
output = rand()%10/3;
if(output > 0)
{
for(i = 0;i < output;i++)
{
goods[i] = '\0';
}
goods_adjust(goods);
printf("output : %d ,%s\n",output,goods);
}
}
void product(char goods[],int num)
{
int i;
int input;
input = rand()%10/3;
if(input > 0)
{
for(i = 0;i < input;i++)
{
goods[num+i] = '#';
}
printf("input : %d ,%s\n",input,goods);
}
}
void *func1()
{
while(1)
{
pthread_cond_wait(&cond1,&mutex);
int num = goods_count(goods);
product(goods,num);
sleep(1);
}
pthread_exit(NULL);
}
void *func2()
{
while(1)
{
pthread_cond_wait(&cond2,&mutex);
int num = goods_count(goods);
consumer(goods,num);
sleep(1);
}
pthread_exit(NULL);
}
void *func3()
{
while(1)
{
pthread_mutex_lock(&signal);
int num = goods_count(goods);
if(num >= 5 && num <= 15)
{
pthread_cond_signal(&cond1);
pthread_cond_signal(&cond2);
}
else if(num < 5)
{
pthread_cond_signal(&cond1);
}
else if( num > 15)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond2);
}
else
{
perror("error");
exit(-1);
}
pthread_mutex_unlock(&signal);
}
pthread_exit(NULL);
}
int main()
{
int num;
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_mutex_init(&signal,NULL);
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond1,NULL);
pthread_cond_init(&cond2,NULL);
pthread_create(&t1,NULL,func1,NULL);
pthread_create(&t2,NULL,func2,NULL);
pthread_create(&t3,NULL,func3,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_mutex_destroy(&signal);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
return 0;
}
结果示例: