If I have a process which creates N threads; namely T1 .... Tn. Assume that N threads are using a lock L to synchronize among themselves. If this process calls fork()
- The new child process created has N threads or just 1 thread ? From this question, looks like its just 1 thread
- The lock L is copied to new memory (physical) location with the same value, right ?
- If answer to question (1) is that only 1 thread gets copied, what happens in new process if T1 had locked L and fork() is called from another thread T2. Will L be always locked ?
The new process has just one running thread initially. That process' copy of the mutex is forever locked, unless explicitly reinitialized or unless the mutex was shared across processes (attribute PTHREAD_PROCESS_SHARED, not everywhere supported).
Here's what the spec has to about this situation say in its discussion of pthread_atfork(), which function was introduced in part to address this unpleasantness:
Consider the case where one thread has a mutex locked and the state
covered by that mutex is inconsistent while another thread calls
fork(). In the child, the mutex is in the locked state (locked by a
nonexistent thread and thus can never be unlocked). Having the child simply reinitialize the mutex is unsatisfactory since this approach does not resolve the question about how to correct or otherwise deal with the inconsistent state in the child.