gpt4 book ai didi

Python thread.Timer() 在我的进程中不起作用

转载 作者:行者123 更新时间:2023-12-01 02:22:20 26 4
gpt4 key购买 nike

import os
import sys
from multiprocessing import Process, Queue
import threading

class Test:
def __init__(self):
print '__init__ is called'

def say_hello_again_and_again(self):
print 'Hello :D'
threading.Timer(1, self.say_hello_again_and_again).start()


test = Test()
#test.say_hello_again_and_again()
process = Process(target=test.say_hello_again_and_again)
process.start()

这是测试代码。

结果:

pi@raspberrypi:~/Plant2 $ python test2.py
__init__ is called
Hello :D

如果我使用 test.say_hello_again_and_again() ,则会重复打印“Hello :D”。

但是,流程没有按我的预期进行。为什么“Hello :D”没有在我的进程中打印?

我的流程中发生了什么?

最佳答案

您的代码有两个问题:

首先:使用start()启动一个进程。这是进行fork,这意味着现在您有两个进程,父进程和子进程并排运行。现在,父进程立即退出,因为在 start() 之后,程序就结束了。要等到子进程完成(在您的情况下永远不会完成),您必须添加 process.join()

I did test your suggestion, but it not works

确实如此。还有第二个问题:您使用 threading.Timer(1, ...).start() 启动一个新线程,但随后立即结束该进程。现在,您不必等到线程启动,因为底层进程会立即终止。您还需要等待线程通过 join() 停止。

现在您的程序如下所示:

from multiprocessing import Process
import threading

class Test:
def __init__(self):
print '__init__ is called'

def say_hello_again_and_again(self):
print 'Hello :D'
timer = threading.Timer(1, self.say_hello_again_and_again)
timer.start()
timer.join()

test = Test()
process = Process(target=test.say_hello_again_and_again)
process.start()
process.join()

但这充其量只是次优,因为您混合了多处理(使用fork来启动独立进程)和线程(在进程内启动线程)。虽然这并不是一个真正的问题,但它使调试变得更加困难(例如上面的代码的一个问题是,由于某种原因,您无法使用 ctrl-c 停止它,因为您生成的进程被操作系统继承并保持运行)。你为什么不这样做呢?

from multiprocessing import Process, Queue
import time

class Test:
def __init__(self):
print '__init__ is called'

def say_hello_again_and_again(self):
while True:
print 'Hello :D'
time.sleep(1)

test = Test()
process = Process(target=test.say_hello_again_and_again)
process.start()
process.join()

关于Python thread.Timer() 在我的进程中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47846063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com