制限付きバッファーでプロデューサー/コンシューマースレッドを操作しようとしています。バッファーの長さは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つ作成します。これらのメソッドは、以下のとおりです。
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);
}
}