【问题标题】:Why won't a Timer from threading work in Process from multiprocess?为什么线程中的计时器不能在多进程的进程中工作?
【发布时间】:2018-07-23 18:38:41
【问题描述】:

我正在尝试在来自multiprocessingProcess 中运行代码。代码使用来自threadingTimer。计时器似乎从未启动。为什么是这样?我能够使用以下代码重现该问题,该代码仅打印一次时间。

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

【问题讨论】:

  • 这可能与this问题有关。

标签: python timer process python-multiprocessing python-multithreading


【解决方案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()

另一种方法是将启动方法设置为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()

【讨论】:

  • 那为什么当我打印threading.enumerate()时似乎有线程在等待?
  • [<_MainThread(MainThread, started 140735590110016)>, <_Timer(Thread-1, started 123145318416384)>],在time.ctime()之后打印时
  • 因此,您正在启动的进程中运行该命令,然后它才会终止。这就说得通了。当进程结束时(例如,当目标方法返回时),则该进程及其所有线程都将被杀死。
猜你喜欢
  • 2021-06-13
  • 2014-03-20
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多