Longjmping back, and back again; Coroutines in C

Ge' Weijers ge at kunivv1.sci.kun.nl
Sat Dec 9 01:00:40 AEST 1989


jerker at enea.se (Jerker W}gberg) writes:

>I am trying to implement coroutines using plain C. My
>application is not time critical, so there is no need for speed,
>being portable is far more important. It would be great if there
>was a way to switch stacks of the processes using just C.

>I have figured out a way to implement this that works fine on a PC
>with MSC 5.1, but wreaks havoc when run on a SUN4. The idea is that
>instead of actually switching stacks, I use the "real" stack but
>swap it in and out of malloced memory.

>1. Can somebody explain why this fails on a SUN4. This is the first
>   program that I ever have tried on a SUN4 so I don't have any
>   idea what happens inside the CPU. Could it be that the SUN4 have
>   some peculiar registers that must be restored but isn't below?

The right question is: can you explain why you expect this to work
on any machine?
This will fail on the Sun4 for more than one reason. It can't be made to
work because of a feature called register windowing. The processor takes
care of saving and restoring registers when a procedure is called. It
uses internal memory for this. Only when it runs out of internal memory
the registers are actually saved on the stack (you have to reserve space
for it.)

>2. Are there more machines out there that probably will throw up
>   when executing this code, apart from CPU's where the stack is
>   growing upward instead of downward. This can be taken care of,
>   but I did not want to clutter the example below.

There is no way I know of to implement coroutines in a portable way.
The peculiarities of each machine force you to change a small part
of your program. For instance: stacks don't always grow from high
to low addresses. This is not the way to do it.

>3. Does anyone know of a better way to do coroutines in C ?

Carefully isolate the machine dependencies, and write a small part in
assembler. Useful knowledge for the Sun4:

	trap #3

flushes the register window. Don't expect a very efficient implementation
of context switching on a SPARC though. There is a lot of context on these
machines, 8 * 16 registers in the worst case. I'm working on this one
(coroutines for the SUN4) but I've not completely figured out how everything
is done. (I'm porting some stuff from a Sun3)

Ge' Weijers


Ge' Weijers                                    Internet/UUCP: ge at cs.kun.nl
Faculty of Mathematics and Computer Science,   (uunet.uu.net!cs.kun.nl!ge)
University of Nijmegen, Toernooiveld 1         
6525 ED Nijmegen, the Netherlands              tel. +3180612483 (UTC-2)



More information about the Comp.lang.c mailing list