Class Thread.Condition

Inheritance graph
Description

Implementation of condition variables.

Condition variables are used by threaded programs to wait for events happening in other threads.

In order to prevent races (which is the whole point of condition variables), the modification of a shared resource and the signal notifying modification of the resource must be performed inside the same mutex lock, and the examining of the resource and waiting for a signal that the resource has changed based on that examination must also happen inside the same mutex lock.

Typical wait operation:

  1. Take mutex lock

  2. Read/write shared resource

  3. Wait for the signal with the mutex lock in released state

  4. Reacquire mutex lock

  5. If needed, jump back to step 2 again

  6. Release mutex lock

Typical signal operation:

  1. Take mutex lock

  2. Read/write shared resource

  3. Send signal

  4. Release mutex lock

Example

You have some resource that multiple treads want to use. To protect this resource for simultaneous access, you create a shared mutex. Before you read or write the resource, you take the mutex so that you get a consistent and private view of / control over it. When you decide that the resource is not in the state you want it, and that you need to wait for some other thread to modify the state for you before you can continue, you wait on the conditional variable, which will temporarily relinquish the mutex during the wait. This way a different thread can take the mutex, update the state of the resource, and then signal the condition (which does not in itself release the mutex, but the signalled thread will be next in line once the mutex is released).

Note

Condition variables are only available on systems with thread support. The Condition class is not simulated otherwise, since that can't be done accurately without continuations.

Note

Signals may currently be sent without holding the lock, but this should be avoided as it may cause the signal to be lost (especially when the signal is not associated with a corresponding change of the shared resource).

See also

Mutex


Method create

Thread.Condition Thread.Condition(Thread.Mutex|void mutex)

Parameter mutex

Optional Mutex that protects the resource that the condition signals for.