Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About threads and callbacks

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.

like image 727
ov1d1u Avatar asked Aug 06 '26 21:08

ov1d1u


1 Answers

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.

like image 176
Ismail Badawi Avatar answered Aug 08 '26 09:08

Ismail Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!