Python多次重新运行线程

时间:2019-01-11 12:57:53

标签: python python-3.x flask

我正在使用Flask创建类似媒体播放列表API的代码。我有一个线程负责播放媒体(检查play_media函数)。只要未从 / stop 请求中“停止”该线程,该线程就在运行。这部分工作完美。问题是当我想在 SECOND 时间重新运行此线程时。

要重新运行它,我创建了另一个端点 / rerun ,因为再次调用 / play 端点将尝试再次启动相同的线程进程。

我正在重播

thread1.run(play_media())

如果我按以下顺序调用端点,则可以正常工作:

  1. thread1.isAlive()->假
  2. / play thread1.isAlive()-> true
  3. /停止thread1.isAlive()-> false
  4. /重新运行thread1.isAlive()-> false

但是,如果重新运行它(4. / stop),我想再次将其停止,则会出现错误:

  

TypeError:run()接受1个位置参数,但给出了2个

错误是指rerun()函数中的这一行:

thread1.run(play_media())

通过更多分析,我发现再次运行线程后,它下面的代码不会触发,这与thread1.start()下面的代码不同。因此,感觉就像卡在 thread1.run(play_media())中一样。任何想法可能是什么原因?

def play_media():
        global playing
        playing = 1
        print(duration)
        while playing == 1:
            for file in media_files:
                if playing == 0:
                    break
                print(file['path'])
                with condition:
                    condition.wait(timeout=duration)
        print('Finished')


condition = threading.Condition()
thread1 = threading.Thread(name='playMedia', target=play_media)


@app.route('/play', methods=['POST'])
def play():
    global duration, media_files, playing
    media = request.json
    duration = media['duration']
    media_files = media['mediaFiles']
    thread1.start()
    return 'Played'


@app.route('/stop')
def stop_media():
    global playing
    playing = 0
    with condition:
        condition.notify()
    return 'Stopped'


@app.route('/rerun')
def rerun():
    global playing
    playing = 1
    thread1.run(play_media())
    # return won't execute
    return 'Rerun'

0 个答案:

没有答案