I am working on a C ++ project that uses pthreads for multithreading, but should also fork from time to time. I read the warnings scattered in the code that memory allocation should never be done after fork , but I did not know exactly why before I found this article . I summed up:
When the main thread is fork s, other threads may be in the middle of a library function call; fork ing does not copy other threads, causing calls to become stuck forever;
malloc uses a global variable and uses locks to ensure thread safety. Therefore, if one of the threads of the parent process is in the middle in the malloc call, the fork ed child process effectively calls the malloc call forever, which can never recover. The same goes for printf , etc.
I realized that this has something to do with reentrancy , a term that is not mentioned in the article. The requirement seems to be equivalent to:
Is this correct, which means that all return functions can be safely used after fork ing? Or am I still missing some unpleasant angles of interaction between pthreads and the traditional UNIX model?
If I'm right, another question arises: malloc , as you know, is not reentrant, but what about C ++ new ? I searched Google for this with few relevant results (mainly due to the difficulty of getting into the correct βnewβ :), but there is at least one statement that new reentrant . There is also a related question regarding the entire C ++ standard library without a satisfactory answer.
PS. For the interested project, C ++ is the shell of the fish . A plug is definitely needed for shells, and threads are used to improve responsiveness.
unix pthreads fork
xiaq
source share