用VI编辑器编写生产者-消费者问题模拟算法
时间: 2024-05-06 08:18:46 浏览: 89
生产者-消费者问题是经典的并发问题,下面是一个用VI编辑器编写的模拟算法:
```
#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 = 0, out = 0; // 缓冲区读写指针
int count = 0; // 缓冲区中的产品数量
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t full; // 缓冲区满条件变量
pthread_cond_t empty; // 缓冲区空条件变量
// 生产者线程函数
void *producer(void *arg) {
int id = *(int *)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) { // 缓冲区满,等待消费者消费
printf("Producer %d: Buffer is full, waiting for consumer...\n", id);
pthread_cond_wait(&full, &mutex);
}
int item = rand() % 100; // 生产一个产品
buffer[in] = item;
printf("Producer %d: Produced item %d into buffer.\n", id, item);
in = (in + 1) % BUFFER_SIZE; // 更新缓冲区写指针
count++;
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 (count == 0) { // 缓冲区空,等待生产者生产
printf("Consumer %d: Buffer is empty, waiting for producer...\n", id);
pthread_cond_wait(&empty, &mutex);
}
int item = buffer[out];
printf("Consumer %d: Consumed item %d from buffer.\n", id, item);
out = (out + 1) % BUFFER_SIZE; // 更新缓冲区读指针
count--;
pthread_cond_signal(&full); // 通知生产者可以生产了
pthread_mutex_unlock(&mutex);
sleep(2);
}
}
int main() {
pthread_t pids[PRODUCER_NUM], cids[CONSUMER_NUM];
int pargs[PRODUCER_NUM], cargs[CONSUMER_NUM];
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, NULL);
// 创建生产者线程
for (int i = 0; i < PRODUCER_NUM; i++) {
pargs[i] = i + 1;
pthread_create(&pids[i], NULL, producer, &pargs[i]);
}
// 创建消费者线程
for (int i = 0; i < CONSUMER_NUM; i++) {
cargs[i] = i + 1;
pthread_create(&cids[i], NULL, consumer, &cargs[i]);
}
// 等待线程结束
for (int i = 0; i < PRODUCER_NUM; i++) {
pthread_join(pids[i], NULL);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
pthread_join(cids[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&full);
pthread_cond_destroy(&empty);
return 0;
}
```
上面的代码中,我们使用了互斥锁和条件变量来实现线程之间的同步和互斥。生产者线程会不断地往缓冲区中生产产品,当缓冲区满时会等待消费者消费;而消费者线程会不断地从缓冲区中消费产品,当缓冲区空时会等待生产者生产。这样可以保证生产者和消费者之间的同步和互斥,避免竞态条件和死锁问题的发生。
阅读全文