3/12/2011

03-12-11 - C Coroutines with Stack

It's pretty trivial to do the C Coroutine thing and just copy your stack in and out. This lets you have C coroutines with stack - but only in a limitted way.

[deleted]

Major crack smoking. This doesn't work in any kind of general way, you would have to find the right hack per compiler, per build setting, etc.

Fortunately, C++ has a mechanism built in that lets you associate some data per function call and make those variable references automatically rebased to that chunk of memory - it's called member variables, just use that!

5 comments:

nothings said...

Does that work on a machine with callee-saved registers? (I.e. does that work on anything except x86?)

Thatcher Ulrich said...

Lua has a native coroutine patch that allegedly works on Windiws, OSX, BSD, and Linux. http://coco.luajit.org/ I see code in the patch for x86, x64, PPC, ARM, MIPS, SPARC and "LP64" (Itanic?). I think you can just pull the C macros out of it and use them, and discard the Lua-specific stuff.

It looks like the windows code uses Fibers. The knock on Fibers that I've heard is that some system calls are not compatible with Fibers, so you have to be careful, or bad things happen. Hearsay, not based on firsthand knowledge, I don't remember details.

Shelwien said...

Did you see that - http://stackoverflow.com/questions/4352451/coroutine-demo-source-2/4352706#4352706 ?

cbloom said...

Hmm.. that looks very similar to the broken one I wrote. Broken in the sense that it's not remotely portable. It's pretty easy to make this work on any one compiler/CPU.

Really not worth bothering with when you can just use member variables.

Shelwien said...

Well, my version is actually portable - I tested it with MSC/IntelC/gcc linux/windows x86/x64/arm. Also it makes sense as a speed optimization (easy to add buffering to bytewise processing loop), and _not_ using any globals/structure fields is a good speed optimization too.
For example, compare http://nishi.dreamhosters.com/u/rc_v3.rar and http://nishi.dreamhosters.com/u/o01_v0.rar

old rants