Coroutines in C

Peter da Silva peter at ficc.uu.net
Sun Aug 13 01:25:21 AEST 1989


This is a followup to a discussion on threads on comp.unix.wizards...

Isn't it about time that there was some effort made to provide a standard
coroutine library in C. I realise that some systems (ones with strict hardware
stacks) wouldn't be able to implement this, but it'd be workable on a wide
variety of systems...

First, let's define a structure containing a co-routine's current context.
This structure is machine dependent, and contains a co-routines stack and
the register set when it's not running.

	context = cocreate(func, stacksize, ...);

This creates a context for a coroutine. The actual arguments need to be
hashed out, but obviously need an initial PC and entry point. The rest
of the arguments could be passed directly to the coroutine when it's started
up.

	cocall(context);

This transfers control to the coroutine until it calls cocall(). It's roughly
equivalent to doing a setjmp() in the current context and a longjmp() into
the context of the new routine. In fact on a lot of systems it could even be
implemented that way. I believe that's how the V7 UNIX kernel did it. Libraries
like the BSD one where longjmp unwinds the stack would of course have to have
an explicit implementation.

	codelete(context);

This deletes the context and cleans up any resources it was using.

These routines together would allow the portable implementation of threads
on a wide variety of systems, if they became widespread. These are strictly
non-preemptive threads, but that's an advantage if you want to call the C
library from more than the mainline... routines in libc are not even vaguely
reentrant, but they are almost all (with the exception of strtok() and a few
others) serially reusable.
-- 
Peter da Silva, Xenix Support, Ferranti International Controls Corporation.
Business: peter at ficc.uu.net, +1 713 274 5180. | "The sentence I am now
Personal: peter at sugar.hackercorp.com.   `-_-' |  writing is the sentence
Quote: Have you hugged your wolf today?  'U`  |  you are now reading"



More information about the Comp.lang.c mailing list