PREV UP NEXT StackThreads/MP: version 0.77 User's Guide

3.12.1: Suspending A Thread

        void st_suspend_thread(st_context_t c);
        typedef struct st_context * st_context_t;

This procedure and the next (resume_context) are the bottom-level primitives on top of which you can build synchronization. We do not expect (and do not want) the programmers to write a program at this level. We still describe them because they are sometimes useful to implement a new synchronization primitive that cannot be easily synthesized from existing ones.

st_suspend_thread suspends (or blocks) a current thread and fills the structure pointed to by C with pieces of information, which we call the `context' of the thread, so that another thread can later resume it. Upon calling this procedure, a field `valid' must be cleared (filled by zero). Here is an example that illustrates the correct use of this procedure:

        struct st_context c[1];
@        c->valid = 0;
@        st_suspend_thread(c);
@           ... (xxx) ...

The control does not immediately return to ... (xxx) .... It will be executed only when somebody explicitly resumes it (by st_resume_context described next).

When C->valid == 0, it indicates that the structure is going to be filled by a context of a thread, but it has not been completely filled. st_suspend_thread sets `valid' to 1 when it is ready to be scheduled. Before anything else, st_suspend_thread checks if C->valid is cleared and signals a runtime error if it is not.

In most cases, you want to store the pointer c to somewhere else before calling st_suspend_thread, so that another thread can find it. Typically, c is stored in some sort of "waiting queue," in which threads are waiting for a condition to be satisfied. To do this, you must do the following steps in the right order.

  1. clear c,
  2. store c somewhere, and
  3. call st_suspend_thread.

The order between 1 and 2 is important; otherwise, another thread may find c and try to resume it, while c has not been completely filled by st_suspend_thread.