9

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?

Rachid K.
  • 4,490
  • 3
  • 11
  • 30
LiKao
  • 10,408
  • 6
  • 53
  • 91
  • I'd never heard of these functions. Are you aware that [POSIX 2001](http://pubs.opengroup.org/onlinepubs/009695399/functions/makecontext.html) already marked them obsolescent in favor of threads? – Fred Foo Feb 13 '12 at 22:16
  • 7
    @larsmans: A pity. Things which are easy with coroutines are much harder with threads. Yes, you *can* emulate coroutines with threads, but only with overhead (synchronization!), and when only one thread is running at any time with all others blocked, it's not really what threading is meant for. – celtschk Feb 13 '12 at 23:53
  • ^^ it gets further complicated when you want to use threads AND coroutines (for parallelism and concurrency, respectively) – James M. Lay Oct 21 '20 at 05:04

1 Answers1

7

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.

leetNightshade
  • 2,673
  • 2
  • 36
  • 47
pmdj
  • 22,018
  • 3
  • 52
  • 103
  • Interesting post (although I feel the best use of coroutines is probably not for fine time slicing or short-lived instances so the overheads cited may be a worst case). Anyway, just to add that I avoid throwing exceptions and otherwise have no problems using make/swapcontext (and ditto Windows fibers) in a [C++ project](http://code.google.com/p/crag/source/browse/src/smp/FiberPosix.cpp). – John McFarlane Dec 18 '12 at 20:15