[英]Python threading loop not continuing?
I'm trying to write a simple program where a timer runs in the background, and every time the timer hits 0, a new image opens up and the timer resets again, for it to continue on and on.我正在尝试编写一个简单的程序,其中一个计时器在后台运行,每次计时器达到 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()
Instead, the image pops up, the counter counts down to 0, then the program ends.相反,图像弹出,计数器向下计数到 0,然后程序结束。
You're not protecting the shared variable t_time in any way so you are always risking race conditions.你没有以任何方式保护共享变量 t_time 所以你总是冒着竞争条件的风险。 Given the sleep calls it would probably work itself out except Anmuviewer isn't a loop.鉴于睡眠调用,它可能会自行解决,除非 Anmuviewer 不是循环。 So you start a thread that immediately counts down t_time by one then Amnuviewer runs and it shows a picture then the second if fails and Anmuviewer ends.因此,您启动一个线程,立即将 t_time 倒计时 1,然后 Amnuviewer 运行并显示一张图片,如果失败,则显示第二张图片,Anmuviewer 结束。 If you replace Anmuviewer with:如果您将 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)
that is probably what you're after and will likely work reliably due to how long the sleep calls are though it could still have race conditions.这可能是您所追求的,并且由于睡眠调用的时间长短,它可能会可靠地工作,尽管它仍然可能存在竞争条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.