Question

Take a look at this trivial python gobject 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 spawns a thread which outputs "HELLO" every second, then enters the gobject main loop. The problem is that it doesn't actually do anything. Why?

$ python a.py 
[...]

If I press CTRL+C, however, it starts to work. Also, removing 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's exactly the same as the first except it tells gobject to run the function g every second. This one sort of works, the spawned thread runs every once in a while, instead of 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()

Running it:

$ 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

And once again, hitting CTRL+C makes the spawned thread work. Why?

This is using the library pygobject-2.28.6.

Was it helpful?

Solution

You need to initialize threading when using gobject. To do so, call

gobject.threads_init()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top