I am having a hard time understanding condition variables.
- Resource contention: condition variables
A condition variable is a queue of processes which are waiting for some event. When the event occurs, the queue will be notified, causing one or more of the stopped processes to be resumed.
What determines whether one or more than one process gets resumed?
Since it is a queue (FIFO), is the first process in always resumed?
Condition variables are used to signal events when the state of some shared resource changes: for example, consider a buffer with readers and a writer, where the readers can only run when there is data in the buffer, and the writer can only refill the buffer when it is empty.
OK, I follow this far.
By providing an atomic "release lock and sleep" operation, a condition variable guards against the "lost notification" problem, which is where the writer adds data to the buffer in between the time that a reader tests it (finding it empty) and goes to sleep.
I do not see how having a "release lock and sleep" operation fixes the "lost notification" problem. Who would use the operation? The reader or the writer or both?
make-condition-variable () [function]
Returns a new condition-variable object for use with CONDITION-WAIT and CONDITION-NOTIFY.
condition-wait (condition-variable lock) [function]
Atomically release LOCK and enqueue the calling process waiting for CONDITION-VARIABLE. The process will resume when another thread has
You probably mean `process' as opposed to `thread'.
notified it using CONDITION-NOTIFY, or we are interrupted,
How would we get interrupted?
or in other implementation-dependent circumstances: the caller must always test on waking that it can proceed, before continuing normal processing.
How does it test that it can proceed? Doesn't that test reintroduce the problem that condition-variables were designed to avoid?
However and for whatever reason the process is resumed, the system always reacquires LOCK before returning to the caller. It is an error to call this unless from the thread that holds LOCK.
In an implementation that does not support multiple processes, this function signals an error.
condition-notify (condition-variable) [function]
Notify one or more of the processes waiting for CONDITION-VARIABLE. The caller needs to acquire the lock associated with the condition variable before calling this.
There has been no mention of "lock associated with condition variable" before. How is this association determined?
In an implementation that does not support multiple processes, this function has no effect.