User guide
3.3. GLOBAL FUNCTIONS 49
The definition of createco is in blib.b and is as follows.
LET createco(fn, size) = VALOF
{ LET c = getvec(size+6)
UNLESS c RESULTIS 0
FOR i = 6 TO size+6 DO c!i := stackword
c!0 := c<<B2Wsh // resumption point
c!1 := currco // parent link
c!2 := colist // colist chain
c!3 := fn // the main function
c!4 := size // the coroutine size
c!5 := c // the new coroutine pointer
colist := c // insert into the list of coroutines
changeco(0, c)
c := fn(cowait(c)) REPEAT
}
The function createco creates a new coroutine by allocating it s stack by the call
gevec(size+6). The variable c holds a pointer to the new coroutine st ack and, as can
been seen, its first six words are initialised to hold sy st em information, as follows.
c!0 resumption point
c!1 parent link
c!2 colist chain
c!3 fn – the main function
c!4 size – the coroutine size
c!5 c – the new coroutine p ointer
The coroutine list colist is also set to c.
The call changeco(0, c) causes the P pointer to be set to c!0 which has been
initialied to the machine address of the base of the new coroutine stack. Execution
continues just after the call, namely at the REPEAT loop in the body of createco,
but in the coroutine environment of the newly created coroutine. The compiled code
for this loop will assume fn, size and c reside in positions 3, 4 and 5 relative to P, ie
in memory locations c!3, c!4 and c!5 and so exec ution behave as (naively) expected.
The first time cowait(c) is called in this loop, execution returns from createco with
the result c which i s the pointer to the newly created coroutine.
When control is next transferred to this new coroutine, the value passed becomes
the result of cowait and hence the argument of fn. If fn(..) returns normally, its
result is assigned to c which is returned to the parent coroutine by the repeated call
of cowait. Thus, if fn is simple, a call of the coroutine convert the value passed, val
say, into fn(val). However, in ge ne r al , fn may contain calls of callco, cowait or
resumeco, and so the situation is not al ways quite so simple .
To help understand the subtle effect of the call of changeco(0,c), look at figure 3.3
showing the state just after the call.