【问题标题】:About threads and callbacks关于线程和回调
【发布时间】:2012-02-11 19:56:29
【问题描述】:

我使用 Python 和线程已经有一段时间了,但我对回调仍有一些疑问。取以下代码:

import threading

def cb_func(data):
    """The callback function"""
    print data

def th_func(callback):
    """The threaded function"""
    # do some work here
    callback('somedata')

thr = threading.Thread(target=th_func, args=(cb_func,)).start()

现在,根据这段代码,函数 cb_func 将在主线程中运行,还是在新创建的 (thr) 线程中运行?我之所以问,是因为我正在使用 GUI 工具包 (GTK),并且在以这种方式调用回调时偶尔会遇到 X 错误(和段错误)(是的,我知道 gobject.idle_add)。

提前感谢您,并对我的愚蠢问题感到抱歉。

【问题讨论】:

    标签: python multithreading thread-safety


    【解决方案1】:

    有一个简单的检查方法,使用current_thread().name

    import threading
    
    def cb_func():
        "The callback function."
        print 'Callback, in thread %s' % threading.current_thread().name
    
    def th_func(callback):
        "The threaded function."
        # ...
        callback()
    
    thr = threading.Thread(target=th_func, args=(cb_func,)).start()
    

    运行此打印(对我来说,在 Ubuntu 11.04,python 2.7.1 上):

    Callback, in thread Thread-1`
    

    换句话说,回调在新创建的线程中运行。

    【讨论】:

      【解决方案2】:

      你被 glib 和线程搞砸了:

      • 在您的示例中,callback/cb_func 将在与 th_func 相同的线程中调用。因为你是在直接打电话。

      • 使用 glib 和 glib.idle_add,您正在安排将在 glib 的主循环中发生的调用。调用是间接的:函数不会在您执行 idle_all 时立即调用,而是稍后调用。

      (现在,如果你开始在一个线程中做某事,然后执行 idle_add(),你就会明白它会发生在不同的线程中。这可能是你得到的错误。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        • 1970-01-01
        • 1970-01-01
        • 2019-06-30
        • 2011-03-31
        相关资源
        最近更新 更多