生产者消费者模型代码实现 c/c++

show me the code


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<sys/mman.h>
#include<pthread.h>
#include<semaphore.h>

sem_t empty;
sem_t full;
int number=0;
pthread_mutex_t mutex;

typedef struct node{
	int date;
	struct node *next;
}Node;

Node *head=NULL;

void* producer(void *arg){
	while(1){
		sem_wait(&empty);
		pthread_mutex_lock(&mutex);
		Node *p=(Node *)malloc(sizeof(Node));
		p->date=rand()%100;
		p->next=head;
		head=p;
		number++;
		printf("produce id = %lu, 当前产品有%d个\t, %d\n", pthread_self(), number, p->date);
		pthread_mutex_unlock(&mutex);
		sem_post(&full);
	}
	return NULL;
}
void* consumer(void *arg){
	while(1){
		sem_wait(&full);
		pthread_mutex_lock(&mutex);
		Node*pp=head;
		head=head->next;
		printf("CONSUMER id = %lu, 当前产品有%d个\t, %d\n", pthread_self(), number, pp->date);
		free(pp);
		if(pp!=NULL)pp=NULL;
		number--;
		pthread_mutex_unlock(&mutex);
		sem_post(&empty);

	}
	return NULL;
}

int main(int argc,char *argv[]){
	
	pthread_t pthid[2];
	
	pthread_mutex_init(&mutex,NULL);
	sem_init(&empty,0,3);
	sem_init(&full,0,0);
	
	pthread_create(&pthid[0],NULL,producer,NULL);
	pthread_create(&pthid[1],NULL,consumer,NULL);
	
	
	// pthread_join(pthid[0],NULL);
	// pthread_join(pthid[1],NULL);
	
	pthread_detach(pthid[0]);
	pthread_detach(pthid[1]);
	
	sleep(3);
	sem_destroy(&empty);
	sem_destroy(&full);
	pthread_mutex_destroy(&mutex);
	exit(0);
}





  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值