All Manuals > LispWorks User Guide and Reference Manual > 15 Multiprocessing > 15.6 Synchronization between threads


15.6.1 Condition variables

A condition variable allows you to wait for some condition to be satisfied, based on the values stored in shared data that is protected by a lock. The condition is typically something like data becoming available in a queue.

The function condition-variable-wait is used to wait for a condition variable to be signalled. It is always called with the lock held, which is automatically released while waiting and reclaimed before continuing. More than one thread can wait for a particular condition variable, so after being notified about the condition changing, you should check the shared data to see if it represents a useful state and call condition-variable-wait again if not.

The function condition-variable-signal is used to wake exactly one thread that is waiting for the condition variable. If no threads are waiting, then nothing happens.

Alternatively, the function condition-variable-broadcast can be used to wake all of the threads that are waiting at the time it is called.

Any threads that wait after the call to condition-variable-signal or condition-variable-broadcast will not be woken until the next call.

In most uses of condition variables, the call to condition-variable-signal or condition-variable-broadcast should be made while holding the lock that waiter used when calling condition-variable-wait for this condition variable. This ensures that the signal is not lost if another thread is just about to call condition-variable-wait.

The function condition-variable-wait-count can be used to determine the current number of threads waiting for a condition variable.

The condition variable implementation in LispWorks aims to comply with the POSIX standard where possible.

condition-variable-wait, condition-variable-signal and condition-variable-broadcast have corresponding functions lock-and-condition-variable-wait, lock-and-condition-variable-signal and lock-and-condition-variable-broadcast. For condition-variable-wait there is also simple-lock-and-condition-variable-wait, which is simpler to use. The lock-and-condition-* functions perform the equivalent of locking and in the scope of the lock doing something and calling the corresponding condition-* function.

The lock-and-condition-* functions not only make it simpler to code, they also make it easier to avoid mistakes, and can optimize some cases (in particular, the quite common case when there is no need to lock on exit from condition-variable-wait). They are the recommended interface.

The lock-and-condition-* functions can be used together with condition-* functions on the same locks and condition variables.

Note: In cases when only one process waits for the condition, using process-wait-local for waiting and process-poke for signalling is easier, and involves less overhead.

LispWorks User Guide and Reference Manual - 21 Dec 2011