How can I create user level threads in Linux. What I understand is that the Pthread library creates kernel level threads. Then how can we create user level threads.
Asked
Active
Viewed 2,123 times
3
-
[Check this](http://stackoverflow.com/questions/8639150/is-pthread-library-actually-a-user-thread-solution), I think creating thread in user-space will create thread in user-level itself – Ravi Dhoriya ツ May 01 '14 at 07:44
-
1Better ask yourself, why do you need user space (aka "green") threads (if that's indeed what you need)? They are not easy to work with and require very careful design considerations to use in programs. – oakad May 01 '14 at 07:45
-
I do not need to create user level threads. Actually I am a trainer and it is just a query to know if it is possible to do so. And if possible then which library calls are to be used – user3282758 May 01 '14 at 07:48
-
You need a separate library, such as this one: http://state-threads.sourceforge.net/ – oakad May 01 '14 at 07:48
1 Answers
4
To implement "green threads" one will need to manipulate the process context to be able to switch between emulated threads of execution. Linux provides a handy API to do so:
- getcontext/setcontext - functions to extract the current execution context and to set it back.
- makecontext/swapcontext - functions to create new execution context and to swap between contexts.
Apart from Linux specific (and very flexible) getcontext()
and friends, C programming language specifications mandate existence of 2 curious functions, setjmp and longjmp. Those can also be used to implement "green" threads, albeit with somewhat more limited functionality.
Naturally, programming with the aforementioned API is difficult, so libraries were created to simplify the task of "green" thread management (one example being the State Threads library).

oakad
- 6,945
- 1
- 22
- 31