linux生产者消费者源程序代码生产者消费者最多生产6个产品
时间: 2024-05-04 20:18:34 浏览: 18
以下是一个简单的基于信号量的Linux生产者消费者源程序代码,其中生产者最多生产6个产品:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5 // 缓冲区大小
#define PRODUCT_MAX 6 // 最多生产产品数
int buffer[BUFFER_SIZE]; // 缓冲区数组
int in = 0, out = 0; // 缓冲区生产者和消费者位置指针
sem_t mutex, empty, full; // 互斥锁和信号量
void *producer(void *arg);
void *consumer(void *arg);
int main(int argc, char *argv[]) {
// 初始化信号量
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
// 创建线程
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// 等待线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// 销毁信号量
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
void *producer(void *arg) {
int i, product;
for (i = 0; i < PRODUCT_MAX; i++) {
// 生产产品
product = rand() % 1000;
sleep(1);
// 尝试获取空缓冲区
sem_wait(&empty);
// 尝试获取互斥锁
sem_wait(&mutex);
// 放入产品
buffer[in] = product;
printf("Producer put product %d into buffer[%d]\n", product, in);
in = (in + 1) % BUFFER_SIZE;
// 释放互斥锁
sem_post(&mutex);
// 发送满缓冲区信号
sem_post(&full);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int i, product;
for (i = 0; i < PRODUCT_MAX; i++) {
// 尝试获取满缓冲区
sem_wait(&full);
// 尝试获取互斥锁
sem_wait(&mutex);
// 取出产品
product = buffer[out];
printf("Consumer get product %d from buffer[%d]\n", product, out);
out = (out + 1) % BUFFER_SIZE;
// 释放互斥锁
sem_post(&mutex);
// 发送空缓冲区信号
sem_post(&empty);
// 消费产品
sleep(1);
}
pthread_exit(NULL);
}
```
在上述代码中,生产者和消费者都在一个无限循环中运行,每次循环中生产者生产一个随机数作为产品,并尝试将其放入缓冲区。如果缓冲区已满,生产者会等待满缓冲区信号。如果互斥锁不可用,生产者也会等待互斥锁。如果成功将产品放入缓冲区,生产者会发送空缓冲区信号。
消费者则尝试从缓冲区中取出一个产品。如果缓冲区为空,消费者会等待空缓冲区信号。如果互斥锁不可用,消费者也会等待互斥锁。如果成功从缓冲区中取出一个产品,消费者会发送满缓冲区信号,并消费该产品,然后进入睡眠状态1秒钟。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)