ov1*_*d1u 3 python multithreading thread-safety
我正在使用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()
Run Code Online (Sandbox Code Playgroud)
现在,根据这段代码,函数cb_func将在主线程中运行,还是在新创建的(thr)线程中运行?我问,因为我正在使用GUI工具包(GTK),并且在以这种方式调用回调时偶尔会出现X错误(和段错误)(是的,我知道gobject.idle_add).
提前谢谢你,对不起我的愚蠢问题.
Ism*_*awi 13
使用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()
Run Code Online (Sandbox Code Playgroud)
运行此打印(对我来说,在Ubuntu 11.04,python 2.7.1):
Callback, in thread Thread-1`
Run Code Online (Sandbox Code Playgroud)
换句话说,回调在新创建的线程中运行.
| 归档时间: |
|
| 查看次数: |
7210 次 |
| 最近记录: |