多个生产者与多个消费者的实现的c语言代码
时间: 2023-06-05 18:47:52 浏览: 99
C语言实现多个生产者和消费者.doc
这里是AI语言模型,以下是多个生产者与多个消费者的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
#define PRODUCER_NUM 3
#define CONSUMER_NUM 2
int buffer[BUFFER_SIZE];
int in = , out = , count = ;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg)
{
int id = *(int *)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(¬_full, &mutex);
}
buffer[in] = rand() % 100;
printf("Producer %d produced %d\n", id, buffer[in]);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&mutex);
sleep(rand() % 3);
}
return NULL;
}
void *consumer(void *arg)
{
int id = *(int *)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (count == ) {
pthread_cond_wait(¬_empty, &mutex);
}
int data = buffer[out];
printf("Consumer %d consumed %d\n", id, data);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&mutex);
sleep(rand() % 3);
}
return NULL;
}
int main()
{
pthread_t producers[PRODUCER_NUM], consumers[CONSUMER_NUM];
int producer_ids[PRODUCER_NUM], consumer_ids[CONSUMER_NUM];
for (int i = ; i < PRODUCER_NUM; i++) {
producer_ids[i] = i;
pthread_create(&producers[i], NULL, producer, &producer_ids[i]);
}
for (int i = ; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i;
pthread_create(&consumers[i], NULL, consumer, &consumer_ids[i]);
}
for (int i = ; i < PRODUCER_NUM; i++) {
pthread_join(producers[i], NULL);
}
for (int i = ; i < CONSUMER_NUM; i++) {
pthread_join(consumers[i], NULL);
}
return ;
}
```
阅读全文