消费者生产者模型

#include <stdio.h>
#include <semaphore.h>
#include <string.h>
#include <pthread.h>

struct data
{
	char *buf[10];
	sem_t full;//控制消费者
	sem_t empty;//控制生产者
	int count;
}data;

pthread_mutex_t mutex;

void *shengchan()
{
	char *buf[] = {"苹果","橘子","香蕉","菠萝","葡萄","梨","橙子","西瓜"};
	int len = sizeof(buf)/sizeof(buf[0]);
	while (1)
	{
		usleep(100000*(rand()%10+1));
		sem_wait(&(data.empty));
		pthread_mutex_lock(&mutex);
		data.buf[data.count] = buf[rand()%len];
		data.count++;
		pthread_mutex_unlock(&mutex);
		sem_post(&(data.full));
	}
	
}

void *xiaofei(void *v)
{
	long num = (long)v;
	
	while (1)
	{
		usleep(100000*(rand()%10+1));
		sem_wait(&(data.full));
		int index = rand()%(data.count);
		printf ("%ld号吃了一个%s,剩余食物:%d\n",num,data.buf[index],data.count-1);
		data.count--;
		char *temp = data.buf[index];
		data.buf[index] = data.buf[data.count];
		data.buf[data.count] = temp;
		pthread_mutex_unlock(&mutex);
		sem_post(&(data.empty));
	}
	
}

int main()
{
	long i;
	for (i = 0;i < 4;i++)
	{
		pthread_t thread;
		pthread_create(&thread,NULL,xiaofei, (void *)(i+1));
		pthread_detach;
	}
	for (i = 0;i < 4;i++)
	{
		pthread_t thread;
		pthread_create(&thread,NULL,shengchan,NULL);
		pthread_detach;
	}
	
	
	sem_init(&data.full,0,0);
	
	sem_init(&data.empty,0,10);
	
	pthread_mutex_init(&mutex,NULL);

	pthread_mutex_destroy(&mutex);
	pthread_exit(NULL);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43667336/article/details/85316744