线程在烧瓶中不起作用

Threading not working in flask

我正在尝试在我的 Flask 应用程序中使用线程,例如:

@app.route('/index')
def index():
    t = threading.Thread(do_sth_else())
    t.start()
    print('ready to response')
    return render_template('index.html')

def do_sth_else():
    time.sleep(5)
    print('sth else done')

在浏览器中调用127.0.0.1:5000/index时,服务器控制台的结果不是我所期望的:

sth else done
ready to response

我希望 do_sth_else() 函数在其他线程中 运行,而 index() 函数继续立即返回响应,这意味着我应该在顺序不同。

所以我想知道:

  1. 为什么 index() 函数一直等到 do_sth_else() 完成
  2. 如何让应用程序按我想要的方式运行

谢谢!

对于 Python 中的实际并行化,您应该使用 multiprocessing 模块来分叉多个并行执行的进程。 Python 线程提供交错,但实际上是串行执行,而不是并行执行。

由于全局解释器锁的存在,这适用于 CPython,否则真正的并发性将与您拥有的 cpu 的数量相关

t = threading.Thread(do_sth_else())do_sth_else() 并将其结果传递给 Thread。 你应该像 t = threading.Thread(do_sth_else).

这样使用它

这个例子如你所愿(在 Python 3.4.3 上测试过)

from time import sleep
from concurrent.futures import ThreadPoolExecutor

# DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
executor = ThreadPoolExecutor(2)


@app.route('/index')
def index():
    executor.submit(do_sth_else)
    print('ready to response')
    return render_template('index.html')


def do_sth_else():
    print("Task started!")
    sleep(10)
    print("Task is done!")