【发布时间】:2017-11-14 07:26:05
【问题描述】:
在tornado中,我们可以使用ThreadPoolExecutor来异步执行调用,但是ThreadPoolExecutor或者@run_on_executor是线程安全的吗? 如果答案是“否”,如何解决资源共享问题?
【问题讨论】:
标签: asynchronous tornado
在tornado中,我们可以使用ThreadPoolExecutor来异步执行调用,但是ThreadPoolExecutor或者@run_on_executor是线程安全的吗? 如果答案是“否”,如何解决资源共享问题?
【问题讨论】:
标签: asynchronous tornado
ThreadPoolExecutor线程安全吗?
ThreadPoolExecutor 是安全的只要你的代码是安全的。它所做的只是在多个线程中运行您的代码。最终,让您的代码线程安全完全取决于您。
如何解决资源共享问题?
通过不共享资源。任何时候你需要对调用主线程的资源做任何事情并在那里做。
在 Tornado 中,您可以使用 ioloop.IOLoop.add_callback 将控制权提交回主线程。因此,您可以在 ThreadPoolExecutor 中运行您的代码,但无论何时您想对资源做任何事情,您都可以将控制权提交回主线程。
例子:
x = 1
def print_x():
global x
if x == 1:
print x
x += 1
如你所见,上面的代码不是线程安全的,因为每个线程都可以修改x。
要以线程安全的方式运行它,您必须在主线程中执行条件检查并修改 x。也就是说,您必须仅在主线程中运行 print_x 函数,如下所示:
x = 1
def print_x():
# run it only in the main thread for thread-safety
global x
if x == 1:
print x
x += 1
def call_print_x():
# this can be run in any thread
# it asks the main thread to run `print_x`
loop = ioloop.IOLoop.current()
loop.add_callback(print_x) # submit control to main thread
【讨论】: