编写代码producer_consumer_many.c,实现多个生产者和多个消费者对缓冲区的操作。
时间: 2024-03-03 13:51:07 浏览: 55
好的,以下是一个简单的实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
#define NUM_PRODUCERS 3
#define NUM_CONSUMERS 2
#define MAX_ITERATIONS 20
int buffer[BUFFER_SIZE];
int count = 0;
int in = 0, out = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
void *producer(void *id) {
int producer_id = *(int *)id;
int i, item;
for (i = 0; i < MAX_ITERATIONS; i++) {
item = rand() % 100; // generate a random number
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) { // buffer full
printf("Producer %d: buffer is full, waiting...\n", producer_id);
pthread_cond_wait(&empty, &mutex);
}
buffer[in] = item;
printf("Producer %d: produced item %d, buffer count is now %d\n", producer_id, item, count + 1);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(&full); // signal to consumers that buffer is not empty
pthread_mutex_unlock(&mutex);
}
printf("Producer %d finished!\n", producer_id);
pthread_exit(NULL);
}
void *consumer(void *id) {
int consumer_id = *(int *)id;
int i, item;
for (i = 0; i < MAX_ITERATIONS; i++) {
pthread_mutex_lock(&mutex);
while (count == 0) { // buffer empty
printf("Consumer %d: buffer is empty, waiting...\n", consumer_id);
pthread_cond_wait(&full, &mutex);
}
item = buffer[out];
printf("Consumer %d: consumed item %d, buffer count is now %d\n", consumer_id, item, count - 1);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(&empty); // signal to producers that buffer is not full
pthread_mutex_unlock(&mutex);
}
printf("Consumer %d finished!\n", consumer_id);
pthread_exit(NULL);
}
int main() {
pthread_t producers[NUM_PRODUCERS], consumers[NUM_CONSUMERS];
int producer_ids[NUM_PRODUCERS], consumer_ids[NUM_CONSUMERS];
int i;
// create producers
for (i = 0; i < NUM_PRODUCERS; i++) {
producer_ids[i] = i;
pthread_create(&producers[i], NULL, producer, &producer_ids[i]);
}
// create consumers
for (i = 0; i < NUM_CONSUMERS; i++) {
consumer_ids[i] = i;
pthread_create(&consumers[i], NULL, consumer, &consumer_ids[i]);
}
// join threads
for (i = 0; i < NUM_PRODUCERS; i++) {
pthread_join(producers[i], NULL);
}
for (i = 0; i < NUM_CONSUMERS; i++) {
pthread_join(consumers[i], NULL);
}
printf("Main thread exiting...\n");
return 0;
}
```
该代码实现了多个生产者和多个消费者对缓冲区的操作,其中缓冲区大小为5,有3个生产者和2个消费者。生产者随机生成一个数字作为生产的物品,消费者从缓冲区中取出物品。当缓冲区满时,生产者会等待,直到有消费者取出物品后才会继续生产;当缓冲区为空时,消费者会等待,直到有生产者生产物品后才会继续消费。在每个生产者和消费者线程完成MAX_ITERATIONS轮操作后,它们会退出线程。最后,主线程会等待所有生产者和消费者线程结束后再退出。
阅读全文