c语言编译模拟生产者消费者问题
时间: 2023-05-22 07:05:15 浏览: 143
生产者消费者问题是一个经典的同步问题,可以用信号量或互斥锁来解决。以下是一个基于C语言的模拟代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
#define PRODUCER_NUM 2
#define CONSUMER_NUM 2
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t mutex, empty, full;
void *producer(void *arg) {
int id = *(int *)arg;
while (1) {
int item = rand() % 100;
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
printf("producer %d produces item %d\n", id, item);
sem_post(&mutex);
sem_post(&full);
sleep(rand() % 2);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int id = *(int *)arg;
while (1) {
sem_wait(&full);
sem_wait(&mutex);
int item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
printf("consumer %d consumes item %d\n", id, item);
sem_post(&mutex);
sem_post(&empty);
sleep(rand() % 2);
}
pthread_exit(NULL);
}
int main() {
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_t producer_threads[PRODUCER_NUM];
pthread_t consumer_threads[CONSUMER_NUM];
int producer_ids[PRODUCER_NUM];
int consumer_ids[CONSUMER_NUM];
for (int i = 0; i < PRODUCER_NUM; i++) {
producer_ids[i] = i;
pthread_create(&producer_threads[i], NULL, producer, (void *)&producer_ids[i]);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i;
pthread_create(&consumer_threads[i], NULL, consumer, (void *)&consumer_ids[i]);
}
for (int i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producer_threads[i], NULL);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumer_threads[i], NULL);
}
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)