【问题标题】:Python thread running twice when called once in mainPython线程在main中调用一次时运行两次
【发布时间】:2017-09-24 10:33:51
【问题描述】:
if __name__ == '__main__':

    t = threading.Thread(target = authtarget)
    t.daemon = True
    t.start()
    print 'running thread'
    app.run(debug=True)

这个 main 在我们的服务器中,app.run 将在其中启动服务器并能够处理请求。我们正在创建的线程是一个计时器,它每 5 秒检查一次特定的 if 语句。但是, t.start() 将创建两个线程,而不是只创建一个。我们已经尝试将 t.start() 更改为 t.run() 但是当我们这样做时,我们永远不会到达 app.run,我们需要运行服务器。

def authtarget():
    sp  = Spotify()
    db = Database()
    resultList = []
    while True:
        time.sleep(5)
        sp.timer(204) 

timer() 是一个我们需要每 5 秒调用一次的函数。 然而,使用我们目前的代码,计时器被调用两次而不是每 5 秒一次

【问题讨论】:

  • 根据@Jean-FrançoisFabre 的评论,app.run() 做了什么?这看起来像是第二个执行线程的明显嫌疑人。
  • app.run() 只是为程序的主要部分运行一些辅助功能。但它没有任何线程调用。
  • “app”是否定义为来自外部库(即 Flask)的对象?以 Flask 为例,带有调试标志的 app.run 可能会导致应用程序加载两次。如果是这种情况,一个可能的解决方案是在线程启动时设置一个环境变量(使用 os.environ),如果已经设置则退出,这样线程就不会运行两次。

标签: python multithreading flask bottle


【解决方案1】:

谢谢大家,我刚刚将 app.run(debug=True) 更改为 app.run(debug=False),这样它就不会运行两次

【讨论】:

  • 我遇到了类似的瓶子问题。通过更改 reloader=False 解决了这个问题。
猜你喜欢
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 2013-04-15
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多