Simplified Toy Scenario :
NOTE : This example uses a singleton. One might justifiably question the wisdom in using that, however, for the purposes of this question I would appreciate it if we could accept the burdens of legacy and ignore that. Thanks.
A parent process imports the mulitprocessing module and creates a child process. The parent then waits for the child to join and later exits by reaching the end of the program.
The child process makes a call to a C/C++ extension to create a C++ object using new. The singleton is implemented as follows :
class MyClass {
public :
static MyClass* getInstance() {
static MyClass* instance = getShared().get();
return instance;
}
private :
static std::shared_ptr<MyClass> getShared() {
static std::shared_ptr<MyClass> sptr(new MyClass());
return sptr;
}
}
The pointer to the newly allocated singleton is not returned to the python child process. The child process exits by reaching the end of the function, at which point it joins the waiting parent process.
The behavior that I am seeing suggests that the answer is :
- No, the singleton's destructor is not called the when the child process exits, and also
- No, the singleton's destructor is not called when the parent process exits.
This is surprising. At the very least I expected the call to atexit when the parent exits to invoke the destructor but it is not doing that. I confirmed that, if the singleton was created in the parent process itself, the singleton's destructor will be invoked on exit.
I am now wondering if this is a some kind of bug with the python multiprocessing module ? This is on python 3.6.
Also, is there a way to force a call to the singleton's destructor when the child exits ?