代码之家  ›  专栏  ›  技术社区  ›  shakedzy

如果用新线程覆盖Python中的线程,会发生什么情况?

  •  0
  • shakedzy  · 技术社区  · 7 年前

    我有一个函数,可以在单独的线程中循环播放声音文件(摘自 this question ),我的函数将其应播放的文件的名称作为参数。

    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()
    

    每次我打电话 play_sound ,我覆盖 sound_thread 并创建一个新线程。旧的会怎么样?它还在后台运行吗?有没有办法终止它?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Mysak0CZ    7 年前

    1) 覆盖时:

    旧的会怎么样?它还在后台运行吗?

    您只覆盖了对线程的引用,线程本身仍在运行。

    有没有办法终止它?

    没有终止线程的干净方法,请参阅: Is there any way to kill a Thread in Python?

    2) 如果要停止线程,应该使用全局var通知线程停止。

    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()
    

    请注意,我还没有完全理解在代码中使用is\u的含义。