生产者消费者问题c语言代码
时间: 2023-09-24 18:06:17 浏览: 124
以下是一个简单的生产者消费者问题的C语言代码:
```c
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE]; // 缓冲区
int count = 0; // 缓冲区中的元素数量
int in = 0; // 缓冲区中下一个空槽位的索引
int out = 0; // 缓冲区中下一个可用元素的索引
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
pthread_cond_t full = PTHREAD_COND_INITIALIZER; // 缓冲区满条件变量
pthread_cond_t empty = PTHREAD_COND_INITIALIZER; // 缓冲区空条件变量
// 生产者线程函数
void* producer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex); // 加锁
// 缓冲区已满,等待消费者消费后再生产
while (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
// 生产一个元素,并将其放入缓冲区
buffer[in] = rand();
printf("producer, in=%d, value=%d\n", in, buffer[in]);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(&full); // 唤醒消费者
pthread_mutex_unlock(&mutex); // 解锁
}
return NULL;
}
// 消费者线程函数
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex); // 加锁
// 缓冲区为空,等待生产者生产后再消费
while (count == 0) {
pthread_cond_wait(&full, &mutex);
}
// 从缓冲区中取出一个元素并消费
int value = buffer[out];
printf("consumer, out=%d, value=%d\n", out, value);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(&empty); // 唤醒生产者
pthread_mutex_unlock(&mutex); // 解锁
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
// 创建生产者线程和消费者线程
if (pthread_create(&producer_thread, NULL, producer, NULL)) {
perror("pthread_create");
exit(1);
}
if (pthread_create(&consumer_thread, NULL, consumer, NULL)) {
perror("pthread_create");
exit(1);
}
// 等待两个线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
```
这段代码实现了一个简单的生产者消费者问题,使用了互斥锁和条件变量来保证缓冲区的正确性。其中,生产者线程生产随机数并将其放入缓冲区,消费者线程从缓冲区中取出随机数并消费。如果缓冲区已满,生产者线程会等待信号,等待消费者线程消费后再进行生产;如果缓冲区为空,消费者线程会等待信号,等待生产者线程生产后再进行消费。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.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)