#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define size_of_buffer 10
sem_t full;//缓冲区内现有的产品数
sem_t empty;//缓冲区内可存有的最大产品数
sem_t mutex;//缓互斥信号灯
int buffer[size_of_buffer];//定义缓冲区
int in = 0;//生产者放入缓冲区指针
int out = 0;//消费者取出产品
void *consumer(){
int ConsumerID = 0;
while(1){
sem_wait(&full);
sem_wait(&mutex);
ConsumerID = buffer[out];//取出产品
out = (out+1)%size_of_buffer;
sem_post(&mutex);
sem_post(&empty);
printf("\tConsumed a consume: %d\n",ConsumerID);
}
}
void *producer(){
int ProductID=0;
while(1){
ProductID++;//加1代表生产了一个产品
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = ProductID;//把产品放入缓冲区
in = (in+1)%size_of_buffer;//指针循环
sem_post(&mutex);
sem_post(&full);
printf("Producted a product: %d\n",ProductID);
sleep(1);
}
}
int main(){
sem_init(&full,0,0);//初始化信号量
sem_init(&empty,0,10);
sem_init(&mutex,0,1);
pthread_t p1ID;//声明线程id
pthread_t p2ID;
pthread_create(&p1ID,0,consumer,0);//穿创建一个线程
pthread_create(&p2ID,0,producer,0);
pthread_join(p1ID,NULL);//以阻塞方式等待指定进程结束
pthread_join(p2ID,NULL);
return 0;
}
linux下使用线程实现生产者消费者问题
最新推荐文章于 2024-09-03 20:17:21 发布