Events

An event summons a thread to action. When a thread receives an event, the scheduler enqueues it for execution at the highest priority.

If the thread was sleeping, the event wakes it up. In some cases the thread was already enqueued for execution, and the scheduler re-enqueues it in the highest priority run queue.

If the thread was already in the highest priority run queue, the event may actually delay its execution by moving the thread to the end of the queue. However subsequent events will not move the thread again until it has run.

Typically the event is sent by another thread, or by the same thread that receives it. It is also possible for the application to send some kinds of events before the scheduler starts to run.

Types of Events

There are three kinds of events:
Messages
A message may convey arbitrary data. It also carries a message type, so that a thread can give different treatment to different types of message.

Enqueues
An enqueue is like a message with no data, except that the message type is not available to the receiving thread. It can wake up a sleeping thread without incurring as much overhead as a message.

Timeouts
A timeout wakes up a sleeping thread after a specified interval, unless something else wakes it up first. A thread can send a timeout only to itself.
Messages and enqueues are similar in many respects. Each may be sent to a single thread, a class of threads (namely those that have subscribed to events of that type), or to all threads. Taken together, they are the principal channel of communication among threads, with the possible exception of global memory.

Timeouts are more specialized. In order to avoid adding overhead to applications that don't need them, Cheap Threads disables timeouts by default. You can enable them at compile time by defining a macro.

Timing Considerations

Whenever a thread sends one or more events to other threads, the scheduler guarantees that all of the recipients will run before the sender can run again. Even if the thread sends an event to itself, all other recipients will run before the sender runs again.

This is one of the few guarantees that Cheap Threads can make about the timing of threads, and it may be useful in some cases.

For example, instead of sending a long message, a thread might just send a pointer to a single copy of the data. Next time the sender runs, it knows that each recipient has received the message, so it can deallocate or overwrite the original. This approach may use less memory and less CPU time than sending a copy of the full message.


Home