生产者和消费者
生产者消费者问题(英语:Producer-consumer problem),也称有限缓冲问题(英语:Bounded-buffer problem),是一个多线程同步问题的经典案例。该问题描述了共享固定大小缓冲区的两个线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。
例: 仓库默认产品为3个,同一时刻只能生产者或消费者中的一个进入仓库(互斥)
如果仓库的产品数量为0,消费者不允许进入仓库购买(条件变量)
1 代码示例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int num = 3;
void *consumption_function(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(0 == num)
{
printf("%s发现仓库为空,等待生产\n", (char *)arg);
pthread_cond_wait(&cond, &mutex);
}
int is_shopping = 0;
if(num > 0)
{
is_shopping = 1;
--num;
printf("%s购买了一个产品,仓库剩余%d个\n", (char *)arg, num);
}
pthread_mutex_unlock(&mutex);
if(is_shopping == 1)
{
printf("%s正在使用产品\n",(char *)arg);
sleep(rand()%5);
}
}
return NULL;
}
void *production_function(void *arg)
{
while(1)
{
sleep(rand()%5);
pthread_mutex_lock(&mutex);
num++;
printf("%s放入一个产品,仓库剩余%d个\n",(char *)arg, num);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, char const *argv[])
{
srand(time(NULL));
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, consumption_function, "消费者A");
pthread_create(&tid2, NULL, consumption_function, "消费者B");
pthread_create(&tid3, NULL, production_function, "生产者A");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)