阅读代码pthread_test_n.c,该代码是告诉大家如何创建n个线程,这n个线程做同样的事情。编写代码producer_consumer_many.c,实现多个生产者和多个消费者对缓冲区的操作。
时间: 2023-11-28 07:48:37 浏览: 80
以下是producer_consumer_many.c的代码实现:
```c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 10
#define PRODUCER_NUM 3
#define CONSUMER_NUM 2
int buffer[BUFFER_SIZE];
int in = 0, 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) {
int id = (int)arg;
while (1) {
pthread_mutex_lock(&mutex);
while ((in + 1) % BUFFER_SIZE == out) {
printf("Producer %d: Buffer is full, waiting...\n", id);
pthread_cond_wait(&full, &mutex);
}
int item = rand() % 100;
buffer[in] = item;
printf("Producer %d: Insert item %d at position %d\n", id, item, in);
in = (in + 1) % BUFFER_SIZE;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consumer(void *arg) {
int id = (int)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (in == out) {
printf("Consumer %d: Buffer is empty, waiting...\n", id);
pthread_cond_wait(&empty, &mutex);
}
int item = buffer[out];
printf("Consumer %d: Remove item %d from position %d\n", id, item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
sleep(2);
}
}
int main() {
pthread_t producer_threads[PRODUCER_NUM];
pthread_t consumer_threads[CONSUMER_NUM];
int i;
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_create(&producer_threads[i], NULL, producer, (void *)i);
}
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_create(&consumer_threads[i], NULL, consumer, (void *)i);
}
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producer_threads[i], NULL);
}
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumer_threads[i], NULL);
}
return 0;
}
```
在该代码中,我们定义了一个缓冲区buffer,和两个指针in和out,分别表示生产者插入的位置和消费者取出的位置。
我们使用了互斥量mutex和条件变量full和empty来保证线程同步。当缓冲区满时,生产者等待full条件变量,当缓冲区为空时,消费者等待empty条件变量。
生产者使用while循环来检查缓冲区是否已满,如果已满则等待full条件变量。当缓冲区未满时,生产者插入一个随机数并更新in指针。然后发送empty条件变量,唤醒正在等待empty条件变量的消费者线程。
消费者使用while循环来检查缓冲区是否为空,如果为空则等待empty条件变量。当缓冲区不为空时,消费者从缓冲区中取出一个数并更新out指针。然后发送full条件变量,唤醒正在等待full条件变量的生产者线程。
在main函数中,我们创建了多个生产者和消费者线程,并使用pthread_join函数等待它们的结束。
阅读全文