ct_wait_on_timeout

The ct_wait_on_timeout function suspends processing for a thread until it receives a message or an enqueue, or until a specified amount of time passes.

Prototype:

int ct_wait_on_timeout( unsigned long interval );

Parameters:

interval
An integer specifying the length of the timeout period, in ticks. By default, the number of ticks per second is defined in time.h as CLOCKS_PER_SEC. If the application needs to redefine the length of a tick, it can call the ct_install_clock function to install a callback function for keeping time.

Return Value:

CT_OKAY if successful, or CT_ERROR if not. Currently the only way to get an error from ct_wait_on_timeout() is to call it when the scheduler is not running.

Discussion:

When a thread calls ct_wait_on_timeout(), the scheduler notes that the thread should wait for an event. When the scheduler regains control, it adds the thread to a list of sleeping threads. The thread will not run again until it receives an event, which may be a message, an enqueue, or a timeout. At that point the scheduler moves the thread from the sleeper queue to the highest priority run queue.

However, if the thread returns without emptying its message queue, the call to ct_wait_on_timeout() will have no effect. The scheduler will enqueue the thread for execution at the highest priority.

If the thread is still asleep when the specified interval has elapsed, the scheduler will awaken it, enqueuing it for execution at the highest priority. If the thread is awakened by a message or an enqueue before the timeout expires, the timeout is cancelled.

The timing starts when the thread calls ct_wait_on_timeout(). However the waiting doesn't start until the thread returns control to the scheduler.

If a thread calls ct_wait_on_timeout() more than once before returning control to the scheduler, the last such call will overrule the earlier calls.

The timeout interval is a minimum time, not a maximum time. In other words, the thread will sleep at least as long as the specified interval (assuming it is not awakened first by some other event), but it may well sleep longer, depending on what the application is doing when the timeout expires. This kind of imprecision is typical for software timers, and is unavoidable for Cheap Threads in particular. The scheduler doesn't have a chance to awaken a sleeping thread until it regains control from whatever other thread is running.

Restrictions:

It makes sense to call ct_wait_on_timeout() only from a thread or user exit, i.e. when the scheduler is running. If you call ct_wait() when the scheduler is not running, it returns CT_ERROR, and puts the scheduler into an error state that you can clear only by calling ct_clear().

The ct_wait_on_timeout function is available only if you compile Cheap Threads with the CT_TIMEOUT macro defined.


Home