多线程(pthreads) & fork

来源:互联网 发布:桌面隐藏软件下载 编辑:程序博客网 时间:2024/06/06 06:44
 子进程hang在了一个mutex上,这才第一次关注多线程情况下fork的问题。

http://cboard.cprogramming.com/linux-programming/99421-pthreads-plus-fork.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.
多线程的进程fork之后,子进程只copy了调用fork的线程,(可能)包括muxtex互斥锁的状态。

pthread_atfork的文档讲了多线程中fork可能带来的问题:
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_atfork.html
http://www.cnblogs.com/zhenjing/archive/2010/12/28/pthread_atfork.html

One problem has to do with state (for example,memory) covered by mutexes. Consider the case where one thread has a mutexlocked and the state covered by that mutex is inconsistent while another threadcallsfork().In the child, the mutex is in the locked state (locked by a nonexistent threadand thus can never be unlocked). Having the child simply reinitialize the mutexis unsatisfactory since this approach does not resolve the question about howto correct or otherwise deal with the inconsistent state in the child.
一个线程给mutex加了锁,然后正在修改受保护的数据,另一个线程调用了fork,那么子进程中这个mutex处于加了锁的状态,但是却没有人来给它解锁了。

解决方案是:
1. 如果可能的话,fork之后尽快调用exec。在此之前,只调用async-signal-safe的库函数。
2. 使用pthread_atfork(),the prepare handler acquires all mutex locks and the other two fork handlers release them.