Synchronisation in fork()ed multithreaded process

2019-08-29 03:08发布

问题:

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()

  1. The new child process created has N threads or just 1 thread ? From this question, looks like its just 1 thread
  2. The lock L is copied to new memory (physical) location with the same value, right ?
  3. 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 ?

回答1:

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.



回答2:

  1. Unless you call fork() before you spawn threads, it will just be on it's own. Forking does not duplicate child thread/processes.
  2. Data in a processes heap is copied to the new process when forked (most likely using copy-on-write) If the lock is stored in the heap, it will get it's own copy, as processes have their own heap.
  3. Using a regular lock (and not a semaphore) any thread can lock/unlock it.