Preemptive multitasking in C/C++: can a running thread be interrupted by some timer and switch between tasks?
Many VMs and other language runtimes using green-threading and such are implemented in these terms; can C/C++ apps do the same?
If so, how?
This is going to be platform dependent, so please discuss this in terms of the support particular platforms have for this; e.g. if there's some magic you can do in a SIGALRM
handler on Linux to swap some kind of internal stack (perhaps using longjmp
?), that'd be great!
I ask because I am curious.
I have been working for several years making async IO loops. When writing async IO loops I have to be very careful not to put expensive to compute computation into the loop as it will DOS the loop.
I therefore have an interest in the various ways an async IO loop can be made to recover or even fully support some kind of green threading or such approach. For example, sampling the active task and the number of loop iterations in a SIGALRM
, and then if a task is detected to be blocking, move the whole of everything else to a new thread, or some cunning variation on this with the desired result.
There was some complaints about node.js in this regard recently, and elsewhere I've seen tantalizing comments about other runtimes such as Go and Haskell. But lets not go too far away from the basic question of whether you can do preemptive multitasking in a single thread in C/C++