在tornado中,我们可以使用ThreadPoolExecutor异步执行调用,但是ThreadPoolExecutor或@run_on_executor是线程安全的吗?如果答案是否定的,那么如何解决资源共享问题呢?
发布于 2017-11-14 22:16:11
是
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 threadhttps://stackoverflow.com/questions/47279937
复制相似问题