Python 为什么赢了';多进程线程中的在制品是否有计时器?
我正试图在Python 为什么赢了';多进程线程中的在制品是否有计时器?,python,timer,process,python-multiprocessing,python-multithreading,Python,Timer,Process,Python Multiprocessing,Python Multithreading,我正试图在多处理中的进程中运行代码。该代码使用线程中的计时器。计时器似乎从未启动过。为什么会这样?我可以用下面的代码重现这个问题,它只打印一次时间 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.ct
多处理
中的进程中运行代码。该代码使用线程
中的计时器
。计时器似乎从未启动过。为什么会这样?我可以用下面的代码重现这个问题,它只打印一次时间
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
问题在于您的进程在计时器
事件触发之前结束。如果您可以保持进程
处于活动状态,它将起作用。有一种方法可以做到这一点:
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
,这会导致已启动的进程等待子线程,而不是如中所述杀死它们。下面是使用该方法的代码:
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()
时会出现线程等待?[,]
,在time.ctime()
之后打印时,您会在启动的进程中运行该命令,然后该进程终止。这是有道理的。当进程结束时(例如,当目标方法返回时),该进程及其所有线程将被终止。这就是问题所在:这可能与问题有关。