编写程序使用Linux操作系统中的信号量机制模拟实现生产者-消费者问题。设有一个生产者和一个消费者缓冲区可以存放产品生产者不断生成产品放入缓冲区消费者不断从缓冲区中取出产品消费产品。使用两个线程来模拟生产者和消费者使用pthread库提供的线程操作需要包含头文件pthreadh使用POSIX的无名信号量机制需要包含头文件semaphoreh
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h>
#define BUFFER_SIZE 10 // 缓冲区大小
sem_t empty; // 空缓冲区信号量 sem_t full; // 满缓冲区信号量 sem_t mutex; // 互斥信号量
int buffer[BUFFER_SIZE]; // 缓冲区 int in = 0; // 生产者放置产品的位置 int out = 0; // 消费者取产品的位置
void *producer(void *arg) // 生产者线程函数 { int item; while (1) { item = rand() % 100; // 生产一个产品 sem_wait(&empty); // 等待空缓冲区 sem_wait(&mutex); // 互斥访问缓冲区 buffer[in] = item; // 将产品放入缓冲区 in = (in + 1) % BUFFER_SIZE; // 更新放置位置 printf("Producer produced item %d\n", item); sem_post(&mutex); // 释放互斥信号量 sem_post(&full); // 增加满缓冲区信号量 } }
void *consumer(void *arg) // 消费者线程函数 { int item; while (1) { sem_wait(&full); // 等待满缓冲区 sem_wait(&mutex); // 互斥访问缓冲区 item = buffer[out]; // 从缓冲区取出产品 out = (out + 1) % BUFFER_SIZE; // 更新取出位置 printf("Consumer consumed item %d\n", item); sem_post(&mutex); // 释放互斥信号量 sem_post(&empty); // 增加空缓冲区信号量 } }
int main() { srand(time(NULL)); // 初始化随机数生成器 pthread_t tid_producer, tid_consumer; sem_init(&empty, 0, BUFFER_SIZE); // 初始化空缓冲区信号量为BUFFER_SIZE sem_init(&full, 0, 0); // 初始化满缓冲区信号量为0 sem_init(&mutex, 0, 1); // 初始化互斥信号量为1 pthread_create(&tid_producer, NULL, producer, NULL); // 创建生产者线程 pthread_create(&tid_consumer, NULL, consumer, NULL); // 创建消费者线程 pthread_join(tid_producer, NULL); // 等待生产者线程结束 pthread_join(tid_consumer, NULL); // 等待消费者线程结束 sem_destroy(&empty); // 销毁空缓冲区信号量 sem_destroy(&full); // 销毁满缓冲区信号量 sem_destroy(&mutex); // 销毁互斥信号量 return 0;
原文地址: https://www.cveoy.top/t/topic/eBbt 著作权归作者所有。请勿转载和采集!