我正嘗試在有界緩衝區中使用生產者/消費者線程。緩衝區的長度是5.我有1個互斥體和2個信號量,它們是以緩衝區的大小開始的空的,並且是滿的,從0開始。C - 生產者/消費者死鎖問題
當我在末尾沒有運行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.
然而,當我在最後的睡眠()運行時,它打印出:
Placed 1 in the buffer at position 0.
The buffer now contains 0 at position 0.
然後它似乎鎖定,但我不確定它爲什麼表現wa無論睡眠是否存在,它都會這樣做。有什麼建議麼?我的主要方法基本上只是做一些聲明,然後創建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);
}
}
我建議你丟掉你的代碼,並用僞代碼重寫任務。或者你可能再次用C重寫它,這通常會幫助我找到這樣的難題。 – 2010-11-05 19:15:30
我可以看到一個(無關的)問題,消費者指數j應由消費者共享。如果它對每個線程都是本地的,它並沒有幫助。讓'j'全球化。 – 2010-11-05 19:16:46
謝謝,我實際上正在計劃在實現多線程時這樣做,但現在我只有1個生產者和1個消費者。 – john 2010-11-05 19:19:23