【问题标题】:What happens to a thread in Python if I overwrite it with a new thread?如果我用新线程覆盖 Python 中的线程会发生什么?
【发布时间】:2018-01-20 23:01:23
【问题描述】:

我有一个函数可以在单独的线程中循环播放声音文件(取自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 并创建一个新线程。旧的会怎样?它还在后台运行吗?有没有办法终止它?

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    1) 覆盖时:

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

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

    有没有办法终止它?

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

    2) 如果你想停止线程,你应该使用全局变量来告诉线程停止。

    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_playing 在您的代码中的含义。

    【讨论】:

    • 我认为stop != is_playing :) 所以,如果我做对了——一旦函数返回,线程就死了?
    猜你喜欢
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多