Bundle
System support for threads and runtime concurrency
Condition
Condition variable: lets a thread holding a ThreadMutex sleep until another thread signals that the state it guards has changed. Wait releases the mutex while it sleeps and holds it again when it returns. A wait may also return without a signal, so always wait in a loop that re-checks the condition. Semaphore, CountDownLatch and Barrier in concurrent.obl are built on it.
Example
class Box {
@mutex : ThreadMutex;
@ready : Condition;
@value : String;
New() {
@mutex := ThreadMutex->New("box");
@ready := Condition->New();
}
method : public : Put(value : String) ~ Nil {
critical(@mutex) {
@value := value;
@ready->Signal();
};
}
method : public : Take() ~ String {
value : String;
critical(@mutex) {
while(@value = Nil) {
@ready->Wait(@mutex);
};
value := @value;
};
return value;
}
}Operations
Wait #
Releases the mutex, sleeps until the condition is signaled, then locks the mutex again. Call it inside critical(mutex), and only once: a mutex locked twice by the same thread stays locked while it waits.
method : public : Wait(mutex:ThreadMutex) ~ NilParameters
| Name | Type | Description |
|---|---|---|
| mutex | ThreadMutex | mutex that guards the condition, held by the caller |
Wait #
Like Wait(mutex), but gives up after the given time
method : public : Wait(mutex:ThreadMutex, millis:Int) ~ BoolParameters
| Name | Type | Description |
|---|---|---|
| mutex | ThreadMutex | mutex that guards the condition, held by the caller |
| millis | Int | longest time to wait, in milliseconds |
Return
| Type | Description |
|---|---|
| Bool | false if the time passed without a signal, true otherwise |