Linux and user-level threads
How to create a user-level thread in Linux. My understanding is that the Pthread library creates kernel-level threads. So how do we create user-level threads.
Solution
To implement a “green thread”, the process context needs to be manipulated to be able to switch between simulated threads of execution. Linux provides a handy API to do this:
- getcontext/setcontext – A function that extracts the current execution context and sets it back.
- makecontext/swapcontext – A function that creates a new execution context and exchanges between contexts.
In addition to the Linux-specific (and very flexible) getcontext(
) and friend, the C programming language specification calls for the existence of 2 strange functions, <a href=”http://man7.org/linux/man-pages/man3/setjmp.3.html” rel=”noreferrer noopener nofollow”>setjmp and These can also be used to implement “green” threads, albeit with limited functionality.
Of course, programming with the above APIs is difficult, so libraries were created to simplify the task of “green” thread management (an example is State Threads library).