Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the makecontext()/swapcontext() functions compatible with C++

In unix environments the makecontext()/swapcontext() family of functions is sometimes used to implement coroutines in C. However these functions directly manipulate the stack and the execution flow. Often when these low level functionalities are quite different when switching from C to C++.

So the question is, if there would be any problem with implementing coroutines using makecontext() and swapcontext(). Of course one obviously would have to take very good care, that an exception could never escape such a coroutine, since there would be no exception handler on the stack for this and the program would most likely segfault. But other than that is there any incompatibility between the way C++ handles things internally and makecontext() and setcontext() modify the execution path?

like image 793
LiKao Avatar asked Feb 13 '12 22:02

LiKao


1 Answers

I've used makecontext()/swapcontext() with C++ code before, and as you say, the main thing to watch out for are exceptions. Beyond that I haven't had any trouble. Despite their obsolescence according to the standard, they're still well-supported by unix-like operating systems. (there is a caveat for Mac OS X: you have to #define _XOPEN_SOURCE before #including the relevant headers.) The rationale for making them obsolete is pretty lame, too - they could have replaced them with a pthreads-like version, where the function pointer takes a single void* argument.

As you say, threads aren't a useful substitute, so I'd go ahead and use swapcontext(). You may also find this blog post interesting for rolling your own version of the functions.

like image 97
pmdj Avatar answered Nov 18 '22 20:11

pmdj