生产者消费者问题C语言代码
时间: 2023-08-18 07:16:15 浏览: 101
C语言编程模拟生产者和消费者问题(附代码程序).pdf
5星 · 资源好评率100%
以下是一个简单的生产者消费者问题的C语言代码,使用信号量来同步生产者和消费者的操作:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5 // 缓冲区大小
#define PRODUCER_NUM 3 // 生产者数量
#define CONSUMER_NUM 2 // 消费者数量
#define ITEM_NUM 10 // 每个生产者/消费者要生产/消费的物品数量
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0, out = 0; // 缓冲区的输入和输出指针
sem_t empty, full, mutex; // 信号量
void *producer(void *arg) {
int id = *((int *)arg);
for (int i = 0; i < ITEM_NUM; i++) {
// 生产一个物品
int item = rand() % 1000;
// 等待空缓冲区
sem_wait(&empty);
sem_wait(&mutex);
// 将物品放入缓冲区
buffer[in] = item;
printf("Producer %d: produce item %d at buffer[%d]\n", id, item, in);
in = (in + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&full);
}
return NULL;
}
void *consumer(void *arg) {
int id = *((int *)arg);
for (int i = 0; i < ITEM_NUM; i++) {
// 等待满缓冲区
sem_wait(&full);
sem_wait(&mutex);
// 取出一个物品
int item = buffer[out];
printf("Consumer %d: consume item %d at buffer[%d]\n", id, item, out);
out = (out + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&empty);
// 消耗物品
sleep(1);
}
return NULL;
}
int main() {
// 初始化信号量
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
// 创建生产者线程
pthread_t producers[PRODUCER_NUM];
int producer_ids[PRODUCER_NUM];
for (int i = 0; i < PRODUCER_NUM; i++) {
producer_ids[i] = i;
pthread_create(&producers[i], NULL, producer, &producer_ids[i]);
}
// 创建消费者线程
pthread_t consumers[CONSUMER_NUM];
int consumer_ids[CONSUMER_NUM];
for (int i = 0; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i;
pthread_create(&consumers[i], NULL, consumer, &consumer_ids[i]);
}
// 等待线程结束
for (int i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producers[i], NULL);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumers[i], NULL);
}
// 销毁信号量
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
```
在这个代码中,生产者线程和消费者线程都会不断地生产和消费物品,直到达到指定数量。它们通过信号量来同步操作,当缓冲区为空时,消费者线程会等待信号量`full`,而生产者线程会等待信号量`empty`。当缓冲区达到满时,生产者线程会等待信号量`full`,而消费者线程会等待信号量`empty`。同时,它们还需要获取互斥量`mutex`来保证缓冲区的读写操作不会冲突。
阅读全文