简体   繁体   中英

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!

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM