C语言调用库函数实现生产者消费者问题

时间:2023-12-29 12:08:44
 #include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h> #define NumOf_Producer 5 //the max num of producer
#define NumOf_Consumer 10 //the max num of consumer
#define Maxnum 10 // the max num of product
sem_t Empty_sem; //the goal of whether the num of product is null
sem_t Full_sem; //the goal of whether the num of product is equal to Maxnum pthread_mutex_t Mutex; //the goal of whether someone use the buff int Producer_id = ;
int Consumer_id = ;
int NowNumOfProduce = ;
void *Producer(void *arg) //the thread of producer
{
int id = Producer_id++;
while()
{
sleep(0.1);
sem_wait(&Full_sem); //when it comes to zero ,it means that the num of product is equal to Maxnum
pthread_mutex_lock(&Mutex); //lock the buff
NowNumOfProduce++;
printf("Producerthread %d product one,the num is:%d \n",id%NumOf_Producer,NowNumOfProduce);
pthread_mutex_unlock(&Mutex);
sem_post(&Empty_sem); //when it comes to ten ,it means there are ten products can be used by consumer
} return ((void *));
} void *Consumer(void *arg)
{
int id = Consumer_id++;
while()
{
sleep(0.2);
sem_wait(&Empty_sem);
pthread_mutex_lock(&Mutex);
NowNumOfProduce--;
printf("Consumerthread %d use product one,the num is:%d \n",id%NumOf_Consumer,NowNumOfProduce);
pthread_mutex_unlock(&Mutex);
sem_post(&Full_sem);
}
return ((void *));
} int main()
{
pthread_t Con[NumOf_Consumer];
pthread_t Pro[NumOf_Producer]; int temp1 = sem_init(&Empty_sem,,);
int temp2 = sem_init(&Full_sem,,Maxnum);
if(temp1&&temp2!=)
{
printf("sem init failed \n");
exit();
} int temp3 = pthread_mutex_init(&Mutex,NULL); if(temp3!=)
{
printf("Mutex init failed \n");
exit();
} for(int i= ;i<NumOf_Producer;i++)
{
int temp4 = pthread_create(&Pro[i],NULL,Producer,(void *)&i);
if(temp4!=)
{
printf("thread create failed !\n");
exit();
}
} for(int i=;i<NumOf_Consumer;i++)
{
int temp5 = pthread_create(&Con[i],NULL,Consumer,(void *)&i);
if(temp5!=)
{
printf("thread create failed !\n");
}
exit();
}
//destroy the thread
for(int i=;i<NumOf_Consumer;i++)
{
pthread_join(Con[i],NULL);
} for(int i=;i<NumOf_Producer;i++)
{
pthread_join(Pro[i],NULL);
} return ;
}
说明:unisted.h是用来调用sleep,pthread.h是linux系统下线程编程的库,semaphore.h是使用信号灯的函数库,至于那些初始化方法,wait方法,post等可以去查查的。如果在编译程序时候出现类似sem_t未定义等问题,需要设置一下link链接,找到linux系统下安装的lib库中的libpthread.so导入进去就好了。