【问题标题】:In tornado, is threadpoolexecutor thread-safe?在龙卷风中,threadpoolexecutor 线程安全吗?
【发布时间】:2017-11-14 07:26:05
【问题描述】:

在tornado中,我们可以使用ThreadPoolExecutor来异步执行调用,但是ThreadPoolExecutor或者@run_on_executor是线程安全的吗? 如果答案是“否”,如何解决资源共享问题?

【问题讨论】:

    标签: asynchronous tornado


    【解决方案1】:

    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
    

    【讨论】:

    • 如果 loop.add_callback 使响应变慢?
    • @shaidiren 没有。线程之间的切换非常快。我的意思是,我认为一微秒的延迟并不重要,是吗?
    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多