Hacker News new | past | comments | ask | show | jobs | submit login

stack switching with setjmp/longjmp can be implemented like this: https://stackoverflow.com/a/8817009/1116739

But it's messy enough that you'd want a library/framework to help you handle it.




POSIX pre-2008 had (and Linux/Glibc and {Free,Net,DragonFly}BSD still have) <ucontext.h> with proper stack switching functions, used as a fallback in a number of coroutine libraries. The fallback status is due to a self-inflicted inefficiency: they save and restore the signal mask, thus still need to go through the kernel (why e.g. Linux does not put signal mask manipulation in the vDSO, I don’t know). POSIX yanked them and now recommends rewriting to use POSIX threads instead, which is asinine.


And the 2008 was about the time that coroutines were gaining popularity again!


Putting each tasklet's stack in different places on the actual stack and jumping between them is inherently unsafe and not portable. You must be sure that each tasklet does not consume too much stack so that it does not overwrite another.

On BSD Unices, you can only longjump back up the stack. Otherwise, longjmp() will call longjmperror() and terminate the program.


> Putting each tasklet's stack in different places on the actual stack and jumping between them is inherently unsafe and not portable. You must be sure that each tasklet does not consume too much stack so that it does not overwrite another.

It's absolutely unsafe and a ridiculous to do, but what's the reasoning for it being unportable? Wouldn't it just be just as unsafe anywhere that C compiles?

> On BSD Unices, you can only longjump back up the stack. Otherwise, longjmp() will call longjmperror() and terminate the program.

The manpage claims that the semantics is not "only jump back up the stack", but rather that you can't longjmp to "[...] an environment that that has already returned". Technically, the tasklet the we're longjmp'ing to never terminates, right?


In any case, you definitely can't do it on Windows and Emscripten (WebAssembly), where longjmp invokes the same stack unwinding behavior as C++ exception handling, rather than just setting some registers and jumping. Windows has its own APIs for tasklets (fibers); no such luck on Emscripten.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: