The Switch Function Approach

So the other approach is to provide a switch function. When called, the switch function would switch into another context. Later, another context may switch back to the first, and the function would return (one call, one return). For symmetry, the function could take as an argument the context to be switched to and return the context it switched from. Unlike no-return/multiple-return, the switch approach is quite analogous to the familiar function call. Indeed, it is quite easy to implement the traditional function: just ``call'' the function by switching to it, and the function, having received the previous context from its own switch instruction, would switch back upon ``return.''

But don't try this for recursive calls! The analogy breaks down here. The important difference is the ``caller'' and the ``callee'' are really the same. Both maintain their own state and their own stack. Both called the switch function. The only difference is the ``caller'' hasn't returned yet, while the ``callee'' has just returned. But unlike in a function, this ``callee'' does not have to return to its ``caller''. Indeed, it can switch to any other context it like, which, in turn, my switch back to the ``caller'' – or the ``caller'' 's switch may never return.

Another important point is that we can treat a context –the state of execution of some thread, including its local variables (stack)– as an object. One thread could potentially freeze another thread, examine its context, perhaps modify some of its variables, and then start it running again. To be able to treat the control flow of a program like its data is a very powerful capability.

In short, the switch function approach, as particular application of the multiple-return/no-return approach, is not as flexible, but provides the functionality we need for multitasking in an abstraction we can deal with.