Reputation: 79
I am a bit confused I would like to know in detail, what happens if a C program with more than one thread creates new processes. Does the behaviour depends on which thread is creating new processes or how many threads create new processes?
Upvotes: 2
Views: 185
Reputation: 224167
With pthreads, only the calling thread is forked in the new process when fork
is called.
From the Linux man page:
The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of
pthread_atfork(3) may be helpful for dealing with problems that this can cause.
There are however some versions of fork
on Solaris that duplicate all threads.
From the Solaris man page:
A call to forkall() or forkallx() replicates in the child process all of the threads (see thr_create(3C) and pthread_create(3C)) in the parent process. A call to fork1() or forkx() replicates only the calling thread in the child process.
A call to fork() is identical to a call to fork1(); only the calling thread is replicated in the child process. This is the POSIX-specified behavior for fork().
In releases of Solaris prior to Solaris 10, the behavior of fork() depended on whether or not the application was linked with the POSIX threads library. When linked with -lthread (Solaris Threads) but not linked with -lpthread (POSIX Threads), fork() was the same as forkall(). When linked with -lpthread, whether or not also linked with -lthread, fork() was the same as fork1().
Upvotes: 4