生产者与消费者模型两例

1

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <time.h>
struct msg
{
	char buf[20];
	sem_t full;
	sem_t empty;
	
}data;


//生产者
void *produce(void *v)
{
	char *buf[]={"苹果","香蕉","芒果","荔枝","猕猴桃","西瓜","桃子","葡萄"};
	int len = sizeof(buf)/sizeof(buf[0]);
	while(1)
	{
		sem_wait(&data.empty);   // p
		usleep(10000*(rand()%10+1));
		strcpy(data.buf,buf[rand()%len]);
		sem_post(&data.full);   // v
	}

}


//消费者
void *consume(void* v)
{
	
	long num = (long)v;
	while(1)
	{
		sem_wait(&data.full);   // p
		usleep(10000*(rand()%10+1));
		printf("%ld消费者吃了一个%s\n",num,data.buf);
		data.buf[0] = '\0';
		sem_post(&data.empty);   // v
	}

}


int main(int argc,char **argv)
{
	srand((unsigned int)time(NULL));
	long i;
	pthread_t thread;
	
	for(i = 0;i < 4;i++)
	{
		pthread_create(&thread, NULL, consume, (void*)(i+1));
		pthread_detach(thread);
	}
	pthread_create(&thread, NULL, produce, NULL);
	pthread_detach(thread);
	
	sem_init(&data.full,0,0);
	sem_init(&data.empty,0,1);
	pthread_exit(NULL);
}


2

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <time.h>
struct msg
{
	char *buf[10];
	sem_t full;
	sem_t empty;
	int count;
}data;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//互斥锁


//生产者
void *produce(void *v)
{
	char *buf[]={"苹果","香蕉","芒果","荔枝","猕猴桃","西瓜","桃子","葡萄","甘蔗","石榴"};
	int len = sizeof(buf)/sizeof(buf[0]);
	while(1)
	{
		usleep(100000*(rand()%10+1));
		sem_wait(&data.empty);   // p
		
		pthread_mutex_lock(&mutex);
		data.buf[data.count]=buf[rand()%len];
		data.count++;

		pthread_mutex_unlock(&mutex);
		sem_post(&data.full);   // v
	}

}


//消费者
void *consume(void* v)
{
	
	long num = (long)v;
	while(1)
	{
		usleep(100000*(rand()%10+1));
		sem_wait(&data.full);   // p
		pthread_mutex_lock(&mutex);
		int index = rand()%data.count;
		
		printf("%ld消费者吃了一个%s 剩余个数:%d\n",num,data.buf[index],data.count-1);
		data.count--;
		char *tmp = data.buf[index];
		data.buf[index] = data.buf[data.count];
		data.buf[data.count] = tmp;
		pthread_mutex_unlock(&mutex);

		sem_post(&data.empty);   // v
	}

}


int main(int argc,char **argv)
{
	srand((unsigned int)time(NULL));
	long i;
	pthread_t thread;
	
	for(i = 0;i < 4;i++)
	{
		pthread_create(&thread, NULL, consume, (void*)(i+1));
		pthread_detach(thread);
	}
	for(i = 0;i < 4;i++)
	{
		pthread_create(&thread, NULL, produce, NULL);
		pthread_detach(thread);
	}
	
	sem_init(&data.full,0,0);
	sem_init(&data.empty,0,10);
	pthread_exit(NULL);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值