How to make thread in C without using POSIX library <pthread.h>

user6327816 picture user6327816 · Nov 8, 2012 · Viewed 10.9k times · Source

I want to implement the multiple threading in C without using any of the POSIX library. Any help would be appreciated.

Not : Don't use fork() or vfork().

Answer

iabdalkader picture iabdalkader · Nov 8, 2012

A thread in Linux is essentially a process that shares memory and resources with its parent. The Linux Kernel does not distinguish between a process and a thread, in other words, there's no concept of a light weight process in Linux like in some other operating systems. Threads in Linux are implemented as standard processes, so it's possible to create a thread using just clone() which is normally called by fork() in the following way:

clone(SIGCHLD, 0);

This clones the signal handlers only, however, with the appropriate flags you can create a thread:

clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, 0);

This is identical to the previous call, except that the address space, filesystem resources, file descriptors and signal handlers are shared by the two processes.

A different approach is to use user-level threads (also called fibres) those are threads of execution implemented at the user-level, which means the OS is unaware of those threads and the scheduling or context switching has to be done at the user-level. Most user-level schedulers are implemented as cooperative schedulers, but it is also possible to implement a preemptive scheduler with a simple round robin scheduling.

Check the clone(2) man page for details and if you want more information I recommend the Linux Kernel Development 3rd edition By Robert Love, (not affiliated with the author in any way) there's a look inside link there you could read some of it online. As for the user-level threads, there's a minimal package written by me, called libutask, that implements both a cooperative and a preemptive scheduler, you can check the source code if you like.

Note1: I have not mentioned UNIX, as far as I know, this is Linux-specific implementation.

Note2: Creating your own threads with clone is not a real world solution, read the comments for the some problems you may have to deal with, it's only an answer to the question is it possible to create threads without using pthreads, in this case the answer is yes.