生产者与消费者

include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
#include<semaphore.h>
#include<stdlib.h>

#define SIZE_OF_BUFFER 10
int buffer[SIZE_OF_BUFFER];//缓冲数组
int in=0,out=0;//采用循环队列方式进行数组的访问

//声明信号量
sem_t full;
sem_t empty;
pthread_mutex_t mutex;//用于互斥

int insert_Item(int item)//插入item
{
if(in>SIZE_OF_BUFFER) return 0;
buffer[in]=item;
in=(in+1)%SIZE_OF_BUFFER;
return 1;
}

int remove_Item()// 移出item 并返回当前移出值
{
if(out>SIZE_OF_BUFFER) return 0;
int removeItem=buffer[out];
out=(out+1)%SIZE_OF_BUFFER;
return removeItem;
}

void * Producer(void * pram)//生产者函数
{
int item;
while(1)
{
   sleep(1);//每一秒生产一个item
   sem_wait(&empty);
   pthread_mutex_lock(&mutex);//互斥
   item=rand()%100+1;
   printf("Producer produced %d",item);
   if(insert_Item(item))
   {
    printf("    Successfully produre~~~/n");
   }
   else
   {
    printf("Failed ~~~/n");
   }
   pthread_mutex_unlock(&mutex); 
   sem_post(&full);
}
}

void * Consumer (void * pram)//消费者函数
{
int removeItem;
while(1)
{
   sleep(3);//每3秒,消费一个item
   sem_wait(&full);
   pthread_mutex_lock(&mutex);//互斥
   removeItem=remove_Item();
   if(removeItem==0)
   {
    printf("Failed ~~~/n");
   }
   else
   {
    printf("Consumer consume %d/n",removeItem);
   }
   pthread_mutex_unlock(&mutex);
   sem_post(&empty);
}
}

int main()
{
pthread_t p_Producer,p_Consumer;//声明生产者和消费者线程
sem_init(&full,0,0);
sem_init(&empty,0,10);
pthread_create(&p_Producer,NULL,(void *)Producer,NULL);//创建生产者线程
pthread_create(&p_Consumer,NULL,(void *)Consumer,NULL);//创建消费者线程
sleep(1000);//主进程睡眠1000秒,sleep函数的参数为秒
//pthread_join(p_Producer,NULL);
//pthread_join(p_Consumer,NULL);
return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值