Python threads not working with pygobject?

Take a look at this trivial gobject python program:

import threading import gobject import time def f(): while True: print "HELLO" time.sleep(1) threading.Thread(target=f).start() gobject.MainLoop().run() 

It generates a stream that outputs "HELLO" every second, then enters the main gobject loop. The problem is that she actually does nothing. Why?

 $ python a.py [...] 

If I press CTRL + C, it starts to work. In addition, deleting the last line in the program ( gobject.MainLoop().run() ) makes it work. Why?

 $ python a.py ^CTraceback (most recent call last): File "a.py", line 11, in <module> gobject.MainLoop().run() KeyboardInterruptHELLO HELLO HELLO HELLO [...] 

Take a look at this second program, it is exactly the same as the first, except that it tells gobject to run the g function every second. This one kind of work generated by a thread works every time, not never. Why?

 import threading import gobject import time def f(): while True: print "HELLO" time.sleep(1) threading.Thread(target=f).start() def g(): print "yo" return True gobject.timeout_add_seconds(1, g) gobject.MainLoop().run() 

Launch:

 $ python b.py HELLOyo yo yo yo HELLO yo yo yo yo yo yo yo HELLO yo yo yo yo ^CTraceback (most recent call last): File "b.py", line 16, in <module> gobject.MainLoop().run() KeyboardInterrupt HELLO HELLO HELLO HELLO HELLO 

Again, pressing CTRL + C makes the spawned thread work. Why?

This is using the pygobject-2.28.6 library.

+4
source share
1 answer

When using gobject you need to initialize streaming . To do this, call

 gobject.threads_init() 
+1
source

All Articles