Python Multiprocessing calling object method [duplicate]

纵饮孤独 提交于 2019-12-11 02:22:29

问题


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.



来源:https://stackoverflow.com/questions/47640541/python-multiprocessing-calling-object-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!