小言_互联网的博客

线程下的生产者和消费者模型

274人阅读  评论(0)

本文讲的是多线程情况下生产者和消费者通过仓库(缓冲区)来传递数据的例子

#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_VALUE 50
//栈结构
char house[MAX_VALUE] = {};
//栈的下标
int top = 0;
//互斥量,确保只有一个线程访问栈顶
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//满仓条件变量(满仓时生产线睡眠)
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
//空仓条件变量(空仓时消费者睡眠)
pthread_cond_t null = PTHREAD_COND_INITIALIZER;

//显示仓库
void show(char* who,char* op,char ch)
{
	printf("%s:",who);
	for(int i=0;i<=top;i++)
	{
		printf("%c",house[i]);
	}
	printf("%s%c\n",op,ch);
}

//生产线程
void* production(void* arg)
{
	char* who = (char*)arg;
	for(;;)
	{
		char ch = 'A' + rand() % 26;
		
		pthread_mutex_lock(&mutex);
		//检查是否满仓
		if(MAX_VALUE <= top)
		{
			printf("%s:满仓",who);
			pthread_cond_wait(&full,&mutex);
		}
		
		show(who,"<-",ch);
		//仓库入仓
		house[top++] = ch;	
		usleep(rand()%100000);
		//确认仓库不空,通知消费者
		pthread_cond_signal(&null);
		//解锁
		pthread_mutex_unlock(&mutex);
		usleep(rand()%100000);
	}
	return NULL;
}

void* consume(void* arg)
{
	char* who = (char*)arg;
	//仓库有货就会一直买
	for(;;)
	{
		//加锁
		pthread_mutex_lock(&mutex);
		//检查空仓
		if(0 == top)
		{
			printf("%s:空仓\n",who);
			pthread_cond_wait(&null,&mutex);
		}
		char ch = house[--top];
		show(who,"->",ch);
		
		usleep(rand()%100000);
		
		pthread_cond_signal(&full);
		pthread_mutex_unlock(&mutex);
		
		usleep(rand()%100000);
	}
}

int main()
{
	srand(time(NULL));
	pthread_t pid[10] = {};
	
	pthread_create(&pid[0],NULL,production,"生产1");
	pthread_create(&pid[1],NULL,consume,"消费1");
    pthread_create(&pid[2],NULL,production,"生产2");
    pthread_create(&pid[3],NULL,consume,"消费2");
    pthread_create(&pid[4],NULL,production,"生产3");
    pthread_create(&pid[5],NULL,consume,"消费3");
    pthread_create(&pid[6],NULL,production,"生产4");
    pthread_create(&pid[7],NULL,consume,"消费4");
    pthread_create(&pid[8],NULL,production,"生产5");
    pthread_create(&pid[9],NULL,consume,"消费5");
    
    for(int i=0;i<10;i++)
    {
    	pthread_join(pid[i],NULL);
    }
}

转载:https://blog.csdn.net/lazymanxxx/article/details/101032479
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场