Path: utzoo!utgpu!watmath!att!tut.cis.ohio-state.edu!brutus.cs.uiuc.edu!wuarchive!texbell!sugar!ficc!peter
From: peter@ficc.uu.net (Peter da Silva)
Newsgroups: comp.lang.c
Subject: Re: Coroutines in C
Message-ID: <5750@ficc.uu.net>
Date: 17 Aug 89 14:16:41 GMT
References: <5663@ficc.uu.net> <14281@haddock.ima.isc.com> <563@augean.OZ> <10109@csli.Stanford.EDU>
Organization: Xenix Support, FICC
Lines: 65

In article <10109@csli.Stanford.EDU>, poser@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@ficc.uu.net, +1 713 274 5180. Fun: peter@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