I'm using the multiprocessing module to run a piece of code on different processes. At some point in the code, I need to know whether the code is being executed by the main process or one of the created child processes.
In all cases I've tried, the name of the current process is always "MainProcess":
>>> import multiprocessing
>>> multiprocessing.current_process().name
'MainProcess'
Is this a python convention I can rely on to be sure that my piece of code is run by the main process (assuming that no other process is named that way)? Otherwise, is there any other way I should use to know which process is executing a piece of code?
Thanks!
It appears that the main process has a different type
than child processes. The main process is mulitprocessing.process._MainProcess
while child processes are multiprocessing.process.Process
. This might be a better way to test for it.
Now, since the name of the _MainProcess
type has a leading underscore, it's meant to be "private," meaning it's an implementation detail that could change. That doesn't seem likely, but you could check to see if the current process is not of type Process
rather than checking to see if it is of type _MainProcess
.