What happens to other threads when one thread forks()?

后端 未结 5 1808
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 14:54

In C++ using pthreads, what happens to your other threads if one of your threads calls fork?

It appears that the threads do not follow. In my case, I am trying to c

5条回答
  •  粉色の甜心
    2020-12-24 15:13

    In POSIX when a multithreaded process forks, the child process looks exactly like a copy of the parent, but in which all the threads stopped dead in their tracks and disappeared.

    This is very bad if the threads are holding locks.

    For this reason, there is a crude mechanism called pthread_atfork in which you can register handlers for this situation.

    Any properly written program module (and especially reusable middleware) which uses mutexes must call pthread_atfork to register some handlers, so that it does not misbehave if the process happens to call fork.

    Besides mutex locks, threads could have other resources, such as thread-specific data squirreled away with pthread_setspecific which is only accessible to the thread (and the thread is responsible for cleaning it up via a destructor).

    In the child process, no such destructor runs. The address space is copied, but the thread and its thread specific value is not there, so the memory is leaked in the child. This can and should be handled with pthread_atfork handlers also.

提交回复
热议问题