GUI Junkie
GUI Junkie

Reputation: 559

Python3 from Thread class to Process

I have some independent threads that would probably gain some speed if I can put them into Process.

I changed class x(Thread): with a def run(self): into a class x(Process)... but the Process doesn't seem to call the run().

What's the correct syntax to set up the Process?

def __init()__:
    Process.__init()__(self, Target=self.run, args=(self,)): ???

Upvotes: 0

Views: 762

Answers (1)

cfi
cfi

Reputation: 11300

You might just be lacking to call instance.start() where instance is the variable which you earlier set to an instance of your class x.

It's easier to answer if you provide a bit more (code) context. From what I see you're mixing up two different ways to setup and start a new thread or process. This is not necessarily bad, it may be intentional. But if it's not, then you're typing more than you need to.

One way is:

p = Process(target=f, args=('bob',))
p.start()
p.join()

with f being any function. The first line sets up a new Process instance, the second line forks and thus starts the (sub)process, and the p.join() waits for it to finish. This is the exact example of the documentation

In the second use case, you subclass from class Process, and then you do not usually specify a target when calling the constructor. run is the default method which is invoked as a fork when you actually call the process.start() method.

class MySubProcess(multiprocessing.Process):
    def __init__(self, *args, **kwargs):
        super().__init__(self)
        # some more specific setup for your class using args/kwargs
    def run(self):
        # here's the code that is going to be run as a forked process
        pass

Then run with

p = MySubProcess(any_args_here)
p.start()
p.join()

If you do not need any arguments then there's no need to define an __init__ constructor for your subclass.

Both approaches allow to switch between threading.Thread and multiprocessing.Process datatypes with very few code changes. Of course the way data sharing works changes, and communication is different for threads and processes.

Upvotes: 2

Related Questions