生产者消费者模型

我们在这里定义一个生产者消费这模型,及供求关系

  • 生产者在没有货时候,买家是不能买到东西的
  • 消费者之间存在原子性操作
  • 总的条件因素应该就是这样了,抱着这个操作,我们完成一个试着完成一个模型。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define CONSUMERS_COUNT 2
#define PRODUCERS_COUNT 2
struct msg
{
	struct msg *next;   
	int num;
};
struct msg *head = NULL;
pthread_cond_t cond; 
pthread_mutex_t mutex;
pthread_t threads[CONSUMERS_COUNT + PRODUCERS_COUNT];
void *consumer(void *p) 
{ 
	int num = *(int*)p;    
	free(p);  
	struct msg *mp;  
	for (;;)
	{ 
		pthread_mutex_lock(&mutex);
		while (head == NULL)  
		{
			printf("%d begin wait a condition...\n", num);
			pthread_cond_wait(&cond, &mutex); 
		}     
		printf("%d end wait a condition...\n", num);   
		printf("%d begin consume product...\n", num);
		mp = head;
		head = mp->next; 
		pthread_mutex_unlock(&mutex);
		printf("Consume %d\n", mp->num); 
		free(mp);
		printf("%d end consume product...\n", num);
		sleep(rand() % 5); } 
}
void *producer(void *p)
{
	struct msg *mp; 
	int num = *(int*)p; 
	free(p);
	for (;;) 
	{
		printf("%d begin produce product...\n", num); 
		mp = (struct msg*)malloc(sizeof(struct msg));   
		mp->num = rand() % 1000 + 1;  
		printf("produce %d\n", mp->num);   
		pthread_mutex_lock(&mutex);   
		mp->next = head; 
		head = mp;     
		printf("%d end produce product...\n", num); 
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);  
		sleep(rand() % 5);
	}
}
int main(void) 
{
	srand(time(NULL));
	pthread_cond_init(&cond, NULL);   
	pthread_mutex_init(&mutex, NULL);
	int i; 
	for (i = 0; i<CONSUMERS_COUNT; i++) 
	{
		int *p = (int*)malloc(sizeof(int)); 
		*p = i;   
		pthread_create(&threads[i], NULL, consumer, (void*)p); 
	}
	for (i = 0; i<PRODUCERS_COUNT; i++)
	{ 
		int *p = (int*)malloc(sizeof(int));     
		*p = i;    
		pthread_create(&threads[CONSUMERS_COUNT + i], NULL, producer, (void*)p); 
	}
	for (i = 0; i<CONSUMERS_COUNT + PRODUCERS_COUNT; i++)    
		pthread_join(threads[i], NULL);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
}

  • 我们主要还是需要记住原子性的约束条件和接口函数不要写错,记住变量加锁,解锁条件。
  • ==其他的实在也不知道需要说一些什么了。
    检验一些结果吧。
    在这里插入图片描述
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值