[英]Python threading loop not continuing?
我正在嘗試編寫一個簡單的程序,其中一個計時器在后台運行,每次計時器達到 0 時,都會打開一個新圖像並且計時器再次重置,以使其繼續運行。
import time
from PIL import Image
import random
import os
import threading
t_time = 5 # seconds i'd like to wait
def Countdown():
global t_time
if t_time > 0:
for i in range(5):
t_time -= 1
time.sleep(1)
print (t_time)
countdown_thread = threading.Thread(target=Countdown)
countdown_thread.start()
def AnmuViewer():
global t_time
if t_time > 0:
random_pic = (random.choice(os.listdir("D:/de_clutter/memez/anmu")))
openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
openPic.show()
if t_time == 0:
t_time = 5 # theoretically this should reset t_time to 5,
# causing Countdown() to start over again. but doesn't
AnmuViewer_thread = threading.Thread(target=AnmuViewer)
AnmuViewer_thread.start()
相反,圖像彈出,計數器向下計數到 0,然后程序結束。
你沒有以任何方式保護共享變量 t_time 所以你總是冒着競爭條件的風險。 鑒於睡眠調用,它可能會自行解決,除非 Anmuviewer 不是循環。 因此,您啟動一個線程,立即將 t_time 倒計時 1,然后 Amnuviewer 運行並顯示一張圖片,如果失敗,則顯示第二張圖片,Anmuviewer 結束。 如果您將 Anmuviewer 替換為:
def AnmuViewer():
global t_time
while True:
if t_time <= 0:
random_pic = (random.choice(os.listdir("D:/de_clutter/memez/anmu")))
openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
openPic.show()
t_time = 5
sleep(0.5)
這可能是您所追求的,並且由於睡眠調用的時間長短,它可能會可靠地工作,盡管它仍然可能存在競爭條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.