next up previous contents
Next: The ISema class Up: Reference of Practical Thread Previous: Switching Threads

The ISync class

# include  <ucr/ISync.h>
class ISync;

This class is intended for synchronization between interrupt handlers and threads. It provides a simple means of blocking a thread until some condition is met. An instance of ISync is a synchronization point that threads and ISRs can safely share, even in an interrupt rich environment. The ISync class takes care of blocking interrupts in the critical times, so the programmer need not worry about such things.

A thread waits for a condition by calling one of the sleep methods of the ISync object. The method tests the condition, and will continue to sleep as long as the condition is false. If the condition is true from the start, then the thread is not suspended.

When a thread or ISR causes a condition to change, it calls the wakeup method of the ISync object. This causes any blocked threads to wakeup and recheck their conditions. The wakeup() method may be called by an ISR or another thread.

When the sleep condition is being tested, the thread is locked in place and interrupts are blocked. This means that the programmer need not add other synchronization primitives around the call to sleep. When a thread or ISR calls wakeup(), many threads may be called and many conditions may be tested. All that evaluate to true will unblock the corresponding thread. (This can cause many threads to be released.) Note that sleep conditions may themselves block, but that is not at all a good idea.

The most general sleep condition is a function that takes a pointer and returns a bool. To test the condition, the ISync object calls the function with the pointer parameter. If the function returns true, the condition is met and the sleep returns. Otherwise, the thread goes back to sleep. The function is always called in the thread context, protected from interrupts.

The simplest sleep condition takes a single pointer to a volatile bool variable. As long as the bool variable is false, the thread sleeps. If an ISR or thread sets the variable to true (and calls wakeup()) the thread continues. This is convenient for waiting for the completion of tasks, such as DMA.

Note that the ISync class uses a ThreadQueue object to contain blocked threads, so in principle a thread can be forced to retest its condition with, or example, the thread_switch() function. This is also true of the classes built up from the ISync class.

next up previous contents
Next: The ISema class Up: Reference of Practical Thread Previous: Switching Threads
Stephen Williams