操作系统实验生产者消费者问题(信号量)仿照的实例程序,分别在生产者和消费者进程的合适的位置加入一些随机睡眠时间。
时间: 2024-05-16 17:18:25 浏览: 25
以下是一个简单的生产者消费者问题的信号量实现,我在生产者和消费者进程的合适位置加入了随机睡眠时间:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void *producer(void *arg)
{
int item, i;
while (1) {
// 随机睡眠 0~2 秒
sleep(rand() % 3);
item = rand() % 100 + 1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer produces item %d at %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *arg)
{
int item, i;
while (1) {
// 随机睡眠 0~2 秒
sleep(rand() % 3);
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Consumer consumes item %d from %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main(int argc, char *argv[])
{
pthread_t p, c;
srand(time(NULL));
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_create(&p, NULL, producer, NULL);
pthread_create(&c, NULL, consumer, NULL);
pthread_join(p, NULL);
pthread_join(c, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
```
在生产者和消费者线程的 while 循环中,我加入了 `sleep(rand() % 3)` 语句,这样每次生产者和消费者执行时,都会随机睡眠 0~2 秒。这样可以模拟生产和消费的随机性,更贴近实际情况。