且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何理解 Tornado 官方关于并发的一条建议 ?

更新时间:2022-10-15 20:44:50

Tornado 的绝大部分 API 都不是线程安全的,从其它线程操作会出(各种奇怪的)问题。只有 IOLoop.add_callback 这一个 API 是线程安全的:

It is safe to call this method from any thread at any time, except from a signal handler. Note that this is the only method in IOLoop that makes this thread-safety guarantee; all other interaction with the IOLoop must be done from that IOLoop‘s thread.

你使用 tornado.concurrent.run_on_executor 就可以了。它自动帮你完成扔任务到线程池、得到结果时取回的逻辑。