Reputation: 571
I am currently learning about concurrency. I understand the purpose that locks and condition variables serve, but in what cases would one want more than one condition variable per lock?
Upvotes: 1
Views: 1521
Reputation: 1318
A condition variable is in fact a queue on which processes can wait (without consuming resources). They do this because they can only proceed when a specific condition holds (hence the name). Multiple condition variables may be useful when different kind of processes must wait for different conditions to hold. A good example is the so-called Producer-consumer problem (http://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem), when two kinds of processes share a common FIFO buffer - producers deposit items in it, consumers extract them. Producers have to occasionally wait until the buffer has at least 1 empty slot to deposit an item to. Similarly, consumers may have to wait when the buffer is empty. The two kinds of processes signal to each other: When a producer deposits an item, it signals to the consumers that the buffer is not empty; when a consumer extracts an item, it signals to the producers that the buffer is not full. Although it is not impossible to solve the problem with using only one condition variable, it is much more natural (and efficient) to use two: one for producers, and one for consumers.
Several other "problems" exist that need a similar approach, e.g. readers-writers and sleeping barber.
Upvotes: 2