我正在尝试在有界缓冲区中使用生产者/消费者线程。缓冲区长度为 5。我有 1 个互斥体和 2 个信号量,从缓冲区大小开始是空的,从 0 开始是满的。
当我在最后没有 sleep() 的情况下运行我的代码时,它会不断产生直到缓冲区完全填满,消耗直到它为空,所以输出如下所示:
Placed 1 in the buffer at position 0.
Placed 2 in the buffer at position 1.
Placed 3 in the buffer at position 2.
Placed 4 in the buffer at position 3.
Placed 5 in the buffer at position 4.
The buffer now contains 0 at position 0.
The buffer now contains 0 at position 1.
The buffer now contains 0 at position 2.
The buffer now contains 0 at position 3.
The buffer now contains 0 at position 4.
但是,当我最后使用 sleep() 运行时,它会打印出:
Placed 1 in the buffer at position 0.
The buffer now contains 0 at position 0.
然后它似乎被锁定了,但我不确定为什么不管是否有睡眠,它的行为方式都是如此。有什么建议么?我的主要方法基本上只是做了一些声明,然后创建 1 个线程来生产和 1 个线程来消费,这些方法如下。
void *producer()
{
int k = 0; //producer index
while (1)
{
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[k] = k+1;
sem_post(&full);
pthread_mutex_unlock(&mutex);
printf("Placed %d in the buffer at position %d.\n", buffer[k], k);
k = (k + 1) % BUFFER_SIZE;
sleep(rand() * 10);
}
}
void *consumer()
{
int j = 0; //consumer index
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
buffer[j] = 0;
sem_post(&empty);
pthread_mutex_unlock(&mutex);
printf("The buffer now contains %d at position %d.\n", buffer[j], j);
j = (j + 1) % BUFFER_SIZE;
sleep(rand() * 10);
}
}