I'm working with Python and threads by some time, but I still have a little doubt about callbacks. Take the following code:
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()
Now, according to this code, function cb_func will run in the main thread, or in the newly created (thr) thread? I'm asking because I'm working with a GUI toolkit (GTK) and I'm occasionally getting X errors (and segfaults) when calling callbacks in this way (yes, I know about gobject.idle_add).
Thank you in advance and sorry for my silly question.
There's an easy way to check, using 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()
Running this prints (for me, on Ubuntu 11.04, python 2.7.1):
Callback, in thread Thread-1`
In other words, the callback runs in the newly created thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With