用c语言编程实现生产者-消费者问题的模拟
时间: 2023-05-26 17:07:01 浏览: 118
```c
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
int in = 0, out = 0;
sem_t full, empty;
pthread_mutex_t mutex;
void *producer(void *param);
void *consumer(void *param);
int main(int argc, char *argv[]) {
pthread_t producer_tid, consumer_tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);
pthread_mutex_init(&mutex, NULL);
pthread_create(&producer_tid, &attr, producer, NULL);
pthread_create(&consumer_tid, &attr, consumer, NULL);
pthread_join(producer_tid, NULL);
pthread_join(consumer_tid, NULL);
sem_destroy(&full);
sem_destroy(&empty);
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
}
void *producer(void *param) {
int item;
while (1) {
item = rand() % 100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer %lu: write %d into buffer[%d]\n", pthread_self(), item, in);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(rand() % 5);
}
}
void *consumer(void *param) {
int item;
while (1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Consumer %lu: read %d from buffer[%d]\n", pthread_self(), item, out);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(rand() % 5);
}
}
```
上述代码实现了一种比较简单的生产者-消费者问题的模拟。其中,使用了信号量和互斥量来控制缓冲区中元素的生产和消费过程。在生产者线程中,生成一个随机数代表一个生产元素,如果缓冲区未满,就将元素加入到缓冲区中,并将in指针指向下一个位置,count加1。在消费者线程中,如果缓冲区不为空,就将元素从缓冲区中取出,将out指针指向下一个位置,count减1。
注意,真实生产环境中需要更严密的错误处理和同步。
阅读全文