4 ms·
Actually, there is: https://en.wikipedia.org/wiki/Setcontext https://en.wikipedia.org/wiki/Setcontext A library I personally recommend, which supports several
by btrask 10y ago
Actually, there is: https://en.wikipedia.org/wiki/Setcontext https://en.wikipedia.org/wiki/Setcontext
A library I personally recommend, which supports several platforms and back-ends: http://byuu.org/library/libco/ http://byuu.org/library/libco/
- deleted 10y ago[deleted]
- sillysaurus3 10y agosetcontext isn't Posix, so corysama is the best kind of correct. But setcontext exists on most flavors of Linux, FreeBSD, and OS X, so you can basically assume it's supported.
- gpderetta 10y agosetcontext was posix until POSIX.2008.
- deleted 10y ago[deleted]
- david-given 10y agoA few years back I built an app which used coroutines extensively (<plug> greylisting SMTP proxy, now abandoned because I don't run my own mailserver any more, http://cowlark.com/spey/ http://cowlark.com/spey/ </plug>). I originally used getcontext/setcontext. Superficially it was really easy, but turned into a goddamned nightmare. The problem is that pthreads gets on really badly with user-allocated stacks; some pthreads implementations find the current thread ID by looking at a magic value on the current thread's stack, and of course with a user-allocated stack this wasn't there. But why was I using pthreads alongside coroutines, you ask? Well, I wasn't. But I was linking to a library which was referring to pthreads symbols, even though it wasn't calling them; which made the linker automatically pull in the thread-safe glibc, so malloc/free ended up wrapping in mutexes... The net effect was bizarre and infrequent crashes that only showed up on machines which weren't mine and that I didn't have access to. I spent months debugging that. Eventually I switched to simulating coroutines using pthreads with a big lock so that only one thread could run at a time. (Which actually turned out to be better, because now I could do some operations properly in parallel.) Beware of setcontext! Bewaaaaaare!
- byuu 10y agoJust a fair warning, setcontext is horrendously slow. It seems to be doing kernel transitions or something. It's about 600 times slower than longjmp with jmpbuf stack pointer hacking, which is itself already about twice as slow as an ideal assembly version.