使用linux操作系统中的信号量机制模拟实现生产者-消费者问题。设有一个生产者和一个消费者实验结果截图
时间: 2024-05-30 09:04:39 浏览: 101
```shell
# 生产者-消费者问题的并发控制
# 生产者线程
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
#define PRODUCER_LOOPS 5
sem_t empty, full, mutex;
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
void *producer(void *arg) {
int i, item;
for (i = 0; i < PRODUCER_LOOPS; i++) {
item = rand() % 100; // 生成随机数作为产品
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = item;
printf("Producer produced item %d at position %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&full);
}
pthread_exit(0);
}
void *consumer(void *arg) {
int i, item;
for (i = 0; i < PRODUCER_LOOPS; i++) {
sem_wait(&full);
sem_wait(&mutex);
item = buffer[out];
printf("Consumer consumed item %d from position %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&empty);
}
pthread_exit(0);
}
int main() {
pthread_t tid_producer, tid_consumer;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
pthread_create(&tid_producer, NULL, producer, NULL);
pthread_create(&tid_consumer, NULL, consumer, NULL);
pthread_join(tid_producer, NULL);
pthread_join(tid_consumer, NULL);
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
```
阅读全文