简体   繁体   中英

What happens to a thread in Python if I overwrite it with a new thread?

I have a function that plays a sound file in loops in separate thread (taken from the answer of this question ), and my function get as an argument the name of the file it should play.

def loop_play(sound_file):
    audio = AudioSegment.from_file(sound_file)
    while is_playing:
        play(audio)

def play_sound(sound_file):
    global is_playing
    global sound_thread
    if not is_playing:
        is_playing = True
        sound_thread = Thread(target=loop_play,args=[sound_file])
        sound_thread.daemon = True
        sound_thread.start()

Every time I call play_sound , I overwrite sound_thread and create a new Thread. What happens to the old one? Is it still running in the background? Is there a way to terminate it?

1) When overwriting:

What happens to the old one? Is it still running in the background?

You have overwritten only reference to the thread, the thread itself is still running.

Is there a way to terminate it?

There is no clean way of terminating threads, see: Is there any way to kill a Thread in Python?

2) If you want to stop the thread, you shoud use global var that tells the thread to stop.

stop = False

def loop_play(sound_file):
    global stop
    audio = AudioSegment.from_file(sound_file)
    while is_playing:
        if stop:
            return
        play(audio)

def play_sound(sound_file):
    global is_playing
    global sound_thread
    global stop
    if not is_playing:
        stop = True
        while sound_thread.isAlive():  # Wait for thread to exit
            sleep(1)
        stop = False
        is_playing = True
        sound_thread = Thread(target=loop_play,args=[sound_file])
        sound_thread.daemon = True
        sound_thread.start()

Note, that i have not fully understood meaning of is_playing in your code.

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