以下は、 Galvin などによるオペレーティング システムの概念で与えられた生産者と消費者の問題の疑似コードです。アル。
n
プールは、それぞれが 1 つの項目を保持できるバッファーで構成されていると想定しています。ミューテックス バイナリ セマフォは、バッファ プールへのアクセスに対して相互排除を提供し、値に初期化されます1
。
//initialization
int n;
semaphore mutex = 1;
semaphore empty = n;
semaphore full = 0;
以下は、プロデューサーの構造の疑似コードです。
while (true)
{
. . .
/* produce an item in next_produced */
. . .
wait(empty);
wait(mutex);
. . .
/* add next produced to the buffer */
. . .
signal(mutex);
signal(full);
}
以下は、コンシューマーの構造の疑似コードです。
while (true)
{
wait(full);
wait(mutex);
. . .
/* remove an item from buffer to next_consumed */
. . .
signal(mutex);
signal(empty);
. . .
/* consume the item in next consumed */
. . .
}
上記は、テキストに関する限りです。もう少し先に進み、バッファの働きも含めてみましょう。バッファchar buffer[n]
として機能する 2 つのプロセス間の共有配列とします。したがって、次のようになります。
/*Structure of the producer- elaborated by me*/
int i=0;
while (true)
{
. . .
/* produce an item in next_produced */
. . .
wait(empty);
//wait(mutex);
. . .
buffer[i]=next_produced;
/* add next produced to the buffer */
i=(i+1)%n;
. . .
//signal(mutex);
signal(full);
}
/*Structure of the consumer elaborated by me*/
int i=0;
while (true)
{
wait(full);
//wait(mutex);
. . .
next_consumer=buffer[i];
/* remove an item from buffer to next_consumed */
i=(i+1)%n;
. . .
//signal(mutex);
signal(empty);
. . .
/* consume the item in next_consumed */
. . .
}
テキストはバッファーにアクセスする前にミューテックスロックを使用していますが (論理的には、バッファーは共有アイテムであるため、相互に排他的な方法でアクセスする必要があります)、アクセス中にミューテックスを使用する必要は厳密にはないと思います。プロデューサーとコンシューマーは同時にバッファーにアクセスできますが、配列の同じ場所に同時にアクセスすることはできないと思います。buffer
同じ場所に同時にアクセスできないため、競合状態の可能性はありません...
これが私が感じていることです。間違っている場合は修正してください。また、間違えた箇所を教えてください。ありがとうございました。