I'm having some problems in understanding how can pthread_atfork
make the child process ensure the mutex states. The manual tells me that use prepare
to acquire lock before a child process is created and use parent
and child
to release the lock in parent process and child. Let's say, parent process p
has a lock which is locked. And it calls fork after register those three fork handler. Both locks in parent and child shall be released, aren't they? But that would not be what we anticipate, right? The lock state has been modified in parent while we only want to change the lock state in child.
I've searched on google and also have also seen stack overflow. I find one problem[https://stackoverflow.com/questions/5473368/pthread-atfork-locking-idiom-broken] close to mine but that answer doesn't dismiss my confusion. I'm not sure if I've misunderstood the usage of the function, and can anyone helm, please.
Let's say, parent process p has a lock which is locked. And it calls fork after register those three fork handler.
The parent process will block in the prepare
, trying to acquire the (already locked elsewhere) lock.
If the thread which is trying to fork
itself holds the lock, then that thread will self-deadlock, and this is a programming bug (fork
ing while holding the lock is a no-no).
If another thread is holding the lock, the forking thread will wait (in prepare
) for that other thread to release the lock, and then everything would be fine in both parent and child after the fork
.
If you know that the forking thread (and not any other thread) has the lock, you could keep that lock across fork
. In that case you would not try to acquire that lock in prepare
, nor release it in either parent
or child
.
P.S. In practice, using fork
in a multi-threaded program which you don't entirely control (i.e. a program which uses external libraries) is nearly impossible to do correctly.