Pthread_atfork lock error?

The standard idiom for using pthread_atfork supposed to be to get all the locks in the pre-fork handler and release them in both the parent and the child handlers. However, as far as I can tell, this is not possible. pthread_mutex_unlock specified either for undefined behavior (in the case of normal, or for mutexes of the default type), or for failure (in the case of recursive or bypass mutexes) if the calling thread is not the owner of the mutex. And in the child handler registered with pthread_atfork , the calling thread is the main thread of the newly created process and, therefore, cannot be the owner of the mutex.

Am I mistaken or the whole idiom pthread_atfork , broken by design and almost impossible to use?

Edit: I also don't see any valid (portable) workaround for the problem. Ideally, you can simply destroy and reinitialize the mutexes in the child process, except that the pthread_mutex_destroy call in the initialized mutex is defined as undefined behavior to accommodate funny implementations in which the mutexes are not PODs but contain a reference to some kernel-level object.

+4
source share
1 answer

I think this is the corresponding text from a person:

When fork () is called, only the calling thread is duplicated in the child process . synchronization variables remain in the same state in the child, as in fork () time is called. Thus, for example, Mutex locks can be held by threads that no longer exist in the child process and any states associated with it can be inconsistent. The parent process can avoid this by explicit code that acquires and releases locks critical for the child through pthread_atfork (). In addition, any critical threads must be recreated and reinitialized to the correct state in the child (also via pthread_atfork ()).

The thread executing the atfork handler in the child is an exact copy of the thread that the atfork handler executed on the parent element and thus has the right to unlock the mutexes.

+1
source

Source: https://habr.com/ru/post/1345720/


All Articles