为什么线程中的Timer不能在多进程中处理进程?

问题描述 投票:2回答:1

我试图在Processmultiprocessing中运行代码。该代码使用Timerthreading。计时器似乎永远不会启动。为什么是这样?我能够使用以下代码重现该问题,该代码仅打印一次。

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

python timer process python-multiprocessing python-multithreading
1个回答
1
投票

问题是你的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()

另一种方法是将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()
© www.soinside.com 2019 - 2024. All rights reserved.