[英]Python thread.Timer() not works in my process
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()
。
我確實測試了您的建議,但是沒有用
確實。 還有第二個問題:您可以使用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
來啟動獨立進程)和線程(在進程內啟動線程)混合在一起。 盡管這並不是真正的問題,但是它會使調試工作變得更加困難(例如,上面的代碼存在一個問題,就是由於某些原因,您生成的進程已被OS繼承並保持運行,因此您無法使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.