多线程(pthreads) & fork

  子进程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 threadcalls fork().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. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值