在Linux或Windows环境下编写程序,建立若干个生产者进程和若干个消费者进程,其中生产者和消费者之间通过一个长度为10的缓冲区进行通信,缓冲区为临界资源。编程实现生产者和消费者之间的同步以及生产者和生产者之间、消费者和消费者之间、生产者和消费者之间的互斥。给我一个简单的示例
时间: 2024-05-15 19:17:40 浏览: 42
编写程序,运用Win32Api实现生产者与消费者使用缓冲区完成生产者与消费者的关系。模拟生产者和消费者的处理过程,程序中演示同步与互斥的关系。
ChitGPT: 您好,我已经准备好回答您的问题。下面是一个简单的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 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 *param);
void *consumer(void *param);
int main(int argc, char *argv[]) {
int producers = 3;
int consumers = 3;
pthread_t *producer_threads = malloc(producers * sizeof(pthread_t));
pthread_t *consumer_threads = malloc(consumers * sizeof(pthread_t));
for (int i = 0; i < producers; i++) {
pthread_create(&producer_threads[i], NULL, producer, NULL);
}
for (int i = 0; i < consumers; i++) {
pthread_create(&consumer_threads[i], NULL, consumer, NULL);
}
for (int i = 0; i < producers; i++) {
pthread_join(producer_threads[i], NULL);
}
for (int i = 0; i < consumers; i++) {
pthread_join(consumer_threads[i], NULL);
}
free(producer_threads);
free(consumer_threads);
exit(0);
}
void *producer(void *param) {
int item;
while (1) {
item = rand() % 100;
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&full, &mutex);
}
buffer[count++] = item;
printf("Producer produced %d\n", item);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *param) {
int item;
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&empty, &mutex);
}
item = buffer[--count];
printf("Consumer consumed %d\n", item);
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
}
```
这个代码示例演示了在 Linux 或 Windows 环境下编写程序,建立若干个生产者进程和若干个消费者进程,并通过长度为 10 的缓冲区进行通信,缓冲区为临界资源。在这个示例中,我们使用了互斥锁和条件变量来实现生产者和消费者之间的同步以及生产者和生产者之间、消费者和消费者之间、生产者和消费者之间的互斥。
阅读全文