CO-ROUTINES - implementation using B functions.

B Implementation:

In B, a co-routine is implemented as a group of functions which have been given their own stack. This independent stack is used by the functions which are part of the co-routine, in the same manner as the main B stack is used by the functions of a regular B program. In fact, the functions of a regular B program themselves constitute a valid co-routine: a group of functions with their own stack. In regular (non-co-routine) B programs, the main B stack and its group of functions constitute the only group of functions and the only stack, and the fact that this group of functions is really an implicitly created co-routine is completely transparent to the user.

The stack given to a co-routine is used only by the functions which are part of that co-routine. This allows the stack to be retained until explicitly destroyed, thus preserving the state of all the functions which make up the co-routine. In keeping with the concept that the states of all co-routines exist concurrently, the states of all B co-routines as preserved on their independent stacks also exist concurrently.

There are special B library subroutines used to create, destroy, and transfer control among co-routines. These all make use of a co-routine's "Function Control Vector (FCV)", which both describes the co-routine's current state and points to its stack. The FCV is also referred to as a "stack descriptor". The FCV contains information about the location, size, and use of the co-routine's stack, the manner in which the co-routine was invoked, and some optional user-supplied vector space.

The co-routine's stack supplies the address at which the co-routine was last suspended. This information is in the form of a return address saved in the linkage section of the function in the co-routine in which execution was suspended. This is the address at which the suspended function and co-routine will resume execution when control next passes to it.

Within a co-routine, which is to say within a group of functions using a common stack, function call and return proceed normally. The same conventions and mechanisms operate as in a regular B program using the main B stack. Just as it is possible to "walk off the end" of the main B stack, you can walk off the end of a co-routine's stack. Non-local GOTOs work, but only within the stack of the co-routine; it is not possible to GOTO a function in another co-routine, since the GOTO searches for its destination on the current stack only. Programming inside a co-routine is almost identical to programming in a regular B program since, as mentioned previously, every B program is actually an implicit co-routine.

Copyright © 1996, Thinkage Ltd.