[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: C coroutines in ANSI C
- From: Mike Pall <mikelu-0508@...>
- Date: Wed, 3 Aug 2005 21:07:27 +0200
Luiz Henrique de Figueiredo wrote:
> I found what seems to be an implementation of C coroutines in ANSI C:
This goes back to a two decades old invention called
"Duff's device", wrapped into a few macros (look at
lc-switch.h). In C it's legal to mix a switch statement
with other control-flow changing statements.
Scroll down to 'EXAMPLE #5a' here and compare:
But this is just a scratch at the surface of the problem.
> There are probably other such libraries around. ET has one (coro) I think.
This is an entirely different thing. In fact my earlier solution
for 'true' C coroutines (with C stack switching) was inspired
by ET's coroutines. After some discussions it became clear that
the hassle of static C stack allocation was the nail in the
coffin for this one. It's not portable, too.
> If someone wants to have a go and see whether these C coroutines mesh well
> with Lua, it'd be nice to see a report here.
The real problem is elsewhere. You need to store the context
somewhere and retrieve it on resume. You need to figure out
stack rewinding in case you want to be able to resume more
than one stack level (I bet you don't want to write your whole
program in one function?).
Oh, and then you'd need to integrate it with the Lua core
and the Lua resume/yield semantics. And hey, while you are
at it, what about metamethods? Umm, and pcall? Right ...
Does this sound familiar?
I couldn't resist: RVM is as simple as I could possibly make it.
It has only 1.5K overhead for all that added functionality.
Oh, and it's ANSI C, too. The source is a tough read, I know.
BTW: LuaJIT doesn't work without RVM, too (it compiles into
machine code and uses the machine stack aka C stack).