为什么线程中的定时器不能在多进程的进程中工作?

Why won't a Timer from threading work in Process from multiprocess?

我正尝试在 multiprocessingProcess 中 运行 编码。该代码使用 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()

输出: Mon Jul 23 14:33:48 2018

问题是您的 ProcessTimer 事件触发之前结束。如果您可以让 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,这会导致启动的进程等待子线程,而不是像 中提到的那样杀死它们。所以这里是使用该方法的代码:

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()