Python Multiprocessing calling object method [dupl

2019-07-13 18:06发布

问题:

This question already has an answer here:

  • Running multiple threads at the same time 1 answer

I want to use Python's multiprocessing module to start a new process which creates some other object and calls that objects loops_forever method.

In my main class I have:

import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever())
print("got here")
my_other_process.start()
print("done")

When I run this code, "got here" never gets printed. loops_forever gets called just above the "got here" print, and control never returns back to my main class.

What am I doing wrong here? I have used multiprocessing before in this fashion:

my_other_process = Process(target=OtherService, kwargs={"address":ADDRESS})
my_other_process.start()

which correctly calls OtherService's init function and runs the init function as a separate process. The only difference is this time I want to call init function AND then run the loops_forever method forever as a separate process.

回答1:

When you do target=my_other_service.loops_forever(), you call loops_forever. To pass it as a function, rather than call it, you would drop the parentheses, like target=my_other_service.loops_forever.