条件変数は、条件を待機するために使用できる同期プリミティブです。
.NETにはネイティブには存在しません。ただし、次のリンクは、SemaphoreSlim、AutoResetEvent、およびMonitorクラスに関して実装された条件変数クラスの100%マネージコードを提供します。これにより、スレッドは条件を待機できます。また、条件が満たされたときに1つ以上のスレッドをウェイクアップできます。さらに、タイムアウトとCancellationTokensをサポートします。
条件を待つには、次のようなコードを記述します。
object queueLock = new object();
ConditionVariable notEmptyCondition = new ConditionVariable();
T Take() {
lock(queueLock) {
while(queue.Count == 0) {
// wait for queue to be not empty
notEmptyCondition.Wait(queueLock);
}
T item = queue.Dequeue();
if(queue.Count < 100) {
// notify producer queue not full anymore
notFullCondition.Pulse();
}
return item;
}
}
次に、別のスレッドで、条件を待機している1つ以上のスレッドをウェイクアップできます。
lock(queueLock) {
//..add item here
notEmptyCondition.Pulse(); // or PulseAll
}