繁体   English   中英

Python线程循环没有继续?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM