加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 关于线程和回调

发布时间:2020-12-20 12:27:34 所属栏目:Python 来源:网络整理
导读:我正在使用 Python和线程一段时间,但我仍然对回调有点怀疑.请使用以下代码: import threadingdef cb_func(data): """The callback function""" print datadef th_func(callback): """The threaded function""" # do some work here callback('somedata')thr
我正在使用 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).

提前谢谢你,对不起我的愚蠢问题.

解决方法

有一种简单的方法可以检查,使用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,)).start()

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

Callback,in thread Thread-1`

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读