c语言实现生产者消费者问题
时间: 2023-11-25 09:06:28 浏览: 237
生产者消费者问题是一个经典的并发问题,它涉及到多个进程或线程之间的同步和互斥。在C语言中,可以使用线程和信号量来实现生产者消费者问题。
具体实现步骤如下:
1. 定义一个共享的缓冲区,可以使用队列或环形缓冲区。
2. 定义一个生产者线程和一个消费者线程。
3. 在生产者线程中,不断生成随机数并将其添加到缓冲区内,并在此之后将 full 计数器加一。
4. 在消费者线程中,检索当前可用的缓冲区,如果满足条件,则从计数器中减去 1,并从缓冲区中读取数据,并在满足特定条件时输出该数据。
5. 使用信号量来实现同步和互斥,保证在生产者没有向缓冲区提交任何内容时,消费者不会读取缓冲区中的任何数字。
下面是一个简单的C语言实现生产者消费者问题的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int count = 0;
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void *producer(void *arg) {
int item;
while (1) {
item = rand() % 100; // 生成随机数
sem_wait(&empty); // 等待空缓冲区
pthread_mutex_lock(&mutex); // 加锁
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
count++;
printf("Producer produced item %d\n", item);
pthread_mutex_unlock(&mutex); // 解锁
sem_post(&full); // 发送满缓冲区信号
}
}
void *consumer(void *arg) {
int item;
while (1) {
sem_wait(&full); // 等待满缓冲区
pthread_mutex_lock(&mutex); // 加锁
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
if (item % 2 == 0) {
printf("Consumer consumed item %d\n", item);
}
pthread_mutex_unlock(&mutex); // 解锁
sem_post(&empty); // 发送空缓冲区信号
}
}
int main() {
pthread_t producer_thread, consumer_thread;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
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(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
```
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)