我正在尝试在 multiprocessing 的 Process 中运行代码。该代码使用 threading 中的 Timer。计时器似乎从未启动过。为什么是这样?我能够使用以下代码重现该问题,它只打印一次时间。
from multiprocessing import Process
from threading import Timer
import time
def print_time_every_5_seconds():
Timer(5,print_time_every_5_seconds).start()
print(time.ctime())
start_process = Process(target=print_time_every_5_seconds)
start_process.start()
输出: 2018 年 7 月 23 日星期一 14:33:48
请您参考如下方法:
问题是您的 Process 在 Timer 事件触发之前结束。如果您可以让 Process 保持事件状态,它就可以工作。这是一种方法:
from multiprocessing import Process, SimpleQueue
from threading import Timer
import time
import functools
def print_time_every_5_seconds(que):
while True:
print(time.ctime())
t = Timer(5,functools.partial(que.put, (None,))).start()
que.get()
if __name__ == '__main__':
que = SimpleQueue()
start_process = Process(target=print_time_every_5_seconds, args=(que,))
start_process.start()
另一种方法是将启动方法设置为 spawn,这会导致启动的进程等待子线程,而不是像 Stackoverflow question mentioned by the OP 中提到的那样杀死它们。 .所以这里是使用该方法的代码:
import multiprocessing as mp
from threading import Timer
import time
def print_time_every_5_seconds():
print(time.ctime())
Timer(5,print_time_every_5_seconds).start()
if __name__ == '__main__':
mp.set_start_method('spawn')
start_process = mp.Process(target=print_time_every_5_seconds)
start_process.start()
