Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: Spawning Process Subclasses

We can create non-forked processes with Python 3's multiprocessing using a created context:

ctx = multiprocessing.get_context('spawn')
p = ctx.Process(target=foo, args=(42,))
p.start()

But suppose I'm working with a subclass of Process. Is there a way to create a Process subclass instance using a method other than fork?

like image 925
charleslparker Avatar asked Aug 20 '26 20:08

charleslparker


2 Answers

Inherit from ctx.Process:

ctx = multiprocessing.get_context('spawn')
class CustomProcess(ctx.Process):
    # define methods
like image 92
Daniel Avatar answered Aug 22 '26 10:08

Daniel


The accepted answer by @Daniel is perfectly fine (and may be more idiomatic), but note also that you can find the appropriately contextualized subclasses of Process deeper in the multiprocessing module (such as multiprocessing.context.SpawnProcess). You can also inherit from these to get the desired behavior.

like image 44
charleslparker Avatar answered Aug 22 '26 10:08

charleslparker