Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A more common method of implementing this that avoids setjmp and longjmp is to code a little assembly to do the stack switch. This is typically faster and easier to port, see:

https://probablydance.com/2013/02/20/handmade-coroutines-for...



Faster I can believe, but how can custom asm be more portable than setjmp/longjmp which are standard since C89?

Although in this particular instance TFA also uses inline assembly to setup the stack, so it's moot.


I'm wrong, I seemed to remember many platforms not supporting them but a quick Google search reveals its just a foggy memory. I was probably thinking about ucontext actually.


Most if not all RTOS's swap threads by saving and restoring the stack and registers. Most of the ones I've seen you can turn off preemption and you then have cooperative threads.

It's much easier to deal with shared memory with cooperative threads at the expense of higher latency.


ucontext is cursed with the behavior of setting and restoring signal masks with each context switch, involving a kernel syscall. If there was a ucontext-lite standard API that did not mess with signal masks you could cheaply switch green threads in userspace.


I did something similar with I implemented coroutines for C (both 32 and 64 bit x86).

[1] https://github.com/spc476/C-Coroutines




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: