NAME
/precompiled/condition - condition variables

DESCRIPTION
/precompiled/condition is a precompiled Pike program that implements condition variables. Condition variables are used by threaded programs to wait for events happening in other threads.

NOTA BENE
Mutex locks are only available on systems with POSIX threads support.

EXAMPLE
// This program implements a fifo that can be used to send
// data between two threads.
inherit "/precompiled/condition": r_cond;
inherit "/precompiled/condition": w_cond;
inherit "/precompiled/mutex": lock;

mixed *buffer = allocate(128);
int r_ptr, w_ptr;

int query_messages() { return w_ptr - r_ptr; }

// This function reads one mixed value from the fifo.
// If no values are available it blocks until a write has been done.
mixed read()
{

mixed tmp;
// We use this mutex lock to make sure no write() is executed
// between the query_messages and the wait() call. If it did
// we would wind up in a deadlock.
object key=lock::lock();
while(!query_messages()) r_cond::wait(key);
tmp=buffer[r_ptr++ % sizeof(buffer)];
w_cond::signal();
return tmp;
}

// This function pushes one mixed value on the fifo.
// If the fifo is full it blocks until a value has been read.
void write(mixed v)
{

object key=lock::lock();
while(query_messages() == sizeof(buffer)) w_cond::wait(key);
buffer[w_ptr++ % sizeof(buffer)]=v;
r_cond::signal();
}

SEE ALSO
/precompiled/mutex


NAME
wait - wait for condition

SYNTAX
void condition->wait();
or
void condition->wait(object mutex_key);

DESCRIPTION
This function makes the current thread sleep until the condition variable is signalled. The optional argument should be the 'key' to a mutex lock. If present the mutex lock will be unlocked before waiting for the condition in one atomical operation. After waiting for the condition the mutex referenced by mutex_key will be re-locked.

SEE ALSO
mutex->lock


NAME
signal - signal a condition variable

SYNTAX
void condition->signal();

DESCRIPTION
Signal wakes up one of the threads currently waiting for the condition.

BUGS
It sometimes wakes up more than one thread.


NAME
broadcast - signal all waiting threads

SYNTAX
void condition->broadcast();

DESCRIPTION
This function wakes up all threads currently waiting for this condition.