简体   繁体   中英

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.

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.

You're not protecting the shared variable t_time in any way so you are always risking race conditions. Given the sleep calls it would probably work itself out except Anmuviewer isn't a loop. 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. If you replace Anmuviewer with:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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