Coroutines in C

Peter da Silva peter at ficc.uu.net
Fri Aug 18 00:16:41 AEST 1989


In article <10109 at csli.Stanford.EDU>, poser at csli.Stanford.EDU (Bill Poser) writes:
> I'm not sure I understand how this solves the problem. Using instance
> variables is pretty much like using statics in C to store the state
> information,

Not really, because it can be concurrently reused. It's more like using
a handle to hold the state information. But as you say it can get to be
a pain if the state information is complex...

> For example, here is a generator that returns pointers to strings
> matching a given regular expression.

Looks good, and coroutines could be used to implement this... you'd
want to pass an extra argument, the context of the calling routine.

Let's say the coroutine functions are:
	context = co_create(entry, stack, ...);
		Creates context, passes arguments to it, transfers
		control to it.
	stuff = co_call(context, stuff);	/* void *stuff */
		stuff will be return value from co_call in other
		context.
	status = co_delete(context);
		Deletes context. It's an error to delete yourself.
	context = co_self();
		Returns own context.

Then we'd call AproposBuiltins like...

	AproposContext = co_create(AproposBuiltins, DEFAULT_STACK, 
		re, co_self());
	while(co_call(AproposContext, NULL)) {
		...
	}
	co_delete(AproposContext);

(changes marked with !, additions with +)

> char *
! AproposBuiltins(re, context)
> regexp *re;
+ context *context;
> {
!    int i = 0;
>    char *retval;
+
+    co_call(context, NULL); /* return from co_create */
> 
>    while(i < comcnt){
!       if(regexec(re,retval = commands[i].name))
!          co_call(context, retval);
!       ++i;
>    }
> 
>    /* If we get here there are no more matches */
> 
>    i = 0;			/* Reset for next search */
!    co_call(context, NULL);
+    blow_up(); /* Should never get here!!!!! */
> }
-- 
Peter da Silva, *NIX support guy @ Ferranti International Controls Corporation.
Biz: peter at ficc.uu.net, +1 713 274 5180. Fun: peter at sugar.hackercorp.com. `-_-'
"Optimization is not some mystical state of grace, it is an intricate act   U
   of human labor which carries real costs and real risks." -- Tom Neff



More information about the Comp.lang.c mailing list