Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiprocessing: name of the main process

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!

like image 779
Romain G Avatar asked Oct 19 '25 22:10

Romain G


2 Answers

Though one can use multiprocessing.current_process(), perhaps a better alternative for it would be to use multiprocessing.parent_process(). For the main process, it will return None.

It was added in Python 3.8, therefore wasn't available at the time of the question.

like image 142
Oleg Avatar answered Oct 22 '25 11:10

Oleg


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.

like image 41
kindall Avatar answered Oct 22 '25 11:10

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!