#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 4//buf size = 4
int buf[N] = {0};//buf init = 0
int putIn = 0;//data in addr
int takeOut = 0;//data out addr
//设计信号量,信号量可以为大小大于1的数
sem_t unoccupied;//
sem_t occupied;//产品数
//设置互斥量(互斥量为0或1)
pthread_mutex_t mutex;//只能有一个线程访问缓冲区
//delay时间
void delay(int len){
int de = rand()%len;
int x;
while(de > 0){
x = rand()%len;
while(x > 0){
x--;
}
de--;
}
}
//生产者
void producer(){
while (1) {
int d = rand()%100;//产品号
delay(25000);//模拟生产时间
sem_wait(&unoccupied);//P操作,将对应的信号量unoccupied减1再与0进行比较大小,
// 入库前判断是否有空位,有空位(比较结果>=0)则后续代码才能执行,否则阻塞当前进程
pthread_mutex_lock(&mutex); //加锁,当一个线程在访问缓冲区时,另一个线程来访问时被阻塞
buf[putIn] = d;
printf("put %d to the buffer at %d\n",buf[putIn],putIn);
putIn++;
if(putIn == N){
putIn = 0;
}
sem_post(&occupied);//V操作,可取信号量+1
pthread_mutex_unlock(&mutex);
}
}
//消费者
void consumer(){
while (1) {
//模拟正在取物品
delay(50000);
sem_wait(&occupied);//P操作,将对应的信号量occupied减1再与0进行比较大小,消费前判断是否有产品,
// 有产品(比较结果>=0)则后续代码才能执行,否则阻塞当前进程
pthread_mutex_lock(&mutex);
printf("Take out %d from the buffer at %d.\n",buf[takeOut],takeOut);
buf[takeOut] = -1;
takeOut++;
if (takeOut == N) {
takeOut = 0;
}
sem_post(&unoccupied);//V操作,可生产空位信号量加1
pthread_mutex_unlock(&mutex);
}
}
int main(){
srand(time(NULL));
//声明厂家消费者线程
pthread_t manufacturer;
pthread_t customer;
//初始化信号量
sem_init(&unoccupied, 0, N);
sem_init(&occupied, 0, 0);
//初始化互斥量
pthread_mutex_init(&mutex, NULL);
//创建线程
pthread_create(&manufacturer, NULL, reinterpret_cast<void *(*)(void *)>(producer), NULL);
pthread_create(&customer, NULL, reinterpret_cast<void *(*)(void *)>(consumer), NULL);
pthread_create(&customer, NULL, reinterpret_cast<void *(*)(void *)>(consumer), NULL);
//阻塞当前线程,直到这两个线程执行结束
pthread_join(manufacturer, NULL);
pthread_join(customer, NULL);
//撤销信号量
sem_destroy(&unoccupied);
sem_destroy(&occupied);
}
os3实验
最新推荐文章于 2024-09-09 23:49:04 发布
该代码示例演示了使用C语言和pthread库解决生产者-消费者问题。通过信号量(semaphore)和互斥锁(mutex)控制对缓冲区的访问,生产者线程生成随机数据并存入缓冲区,消费者线程则从缓冲区取出数据。每个线程都有相应的延迟函数模拟实际生产或消费的时间。
摘要由CSDN通过智能技术生成