生产者与消费者

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;
}

你可能感兴趣的:(生产者)