Coroutines, pt. 2
[I just posted these questions to Apple’s darwin-userlevel mailing list, but they’re also worth cc:ing here as a follow-up to my last post.]
I’ve been experimenting this week with coroutines. Typically these are implemented as a type of cooperative thread, since each coroutine needs a separate stack and register set. I adapted Steve Dekorte’s libCoroutine, which basically just uses ucontext, with malloc’ed stacks.
It strikes me that ucontext is basically no lighter-weight than a pthread, in terms of address-space usage and context switch speed. Is that true? Or is there additional overhead to pthreads besides the stack + registers?
If so, then it might be simpler just to use pthreads, since the API is already in place, and existing system facilities (like ObjC and C++ exceptions, and Cocoa autorelease pools) already know how to work with them. But the cooperative scheduling of coroutines is a bonus in some ways, as it makes the flow of control more deterministic and reduces the need for complex locking and synchronization.
So my second question is whether there’s a clean way to implement cooperative scheduling of pthreads1, i.e. to have a set of threads that transfer control within themselves only via some sort of “yield” call, not by pre-emption? I’ve seen this implemented, for tutorial purposes, in Java using a shared lock. However, a coroutine transfers control to an explicitly-named other coroutine; it’s not at the whim of the thread scheduler. How would one implement that in pthreads? I’m guessing it would involve a lock per thread; but I’m not familiar with the details of the pthreads primitives or API, so advice would be appreciated.
—Jens
1 Yes, I’m aware that cooperative scheduling means you don’t get all the performance benefits of multicore CPUs. I’m not concerned about that because, frankly, my application code uses minimal CPU time; it’s always waiting for sockets, CoreAudio background threads, or user input. So the benefits of threading my code aren’t worth the complexity and error-prone-ness of thread-safety.
Previously: Coroutines in Objective-C
Next Post: Stickies makes its music-video debut!
- By
- Jens Alfke
- On
- May 3, 2008
- at
- 9:21 am
- As
- Computers
- See
- 8 comments;
- Add
- your comment
8 Comments:
comments feed | trackback uri