Python, thread and gobject

I am writing a framework program using pygtk. The main program performs the following actions:

  • Create a watchdog stream to monitor some resource
  • Create a client to receive data from a socket
  • call gobject.Mainloop()

but it seems that after my program enters Mainloop, the control chain will not work either.

My workaround is to use gobject.timeout_add to start the monitor.

But why doesn't creating another thread work?

Here is my code:

 import gobject import time from threading import Thread class MonitorThread(Thread): def __init__(self): Thread.__init__(self) def run(self): print "Watchdog running..." time.sleep(10) def main(): mainloop = gobject.MainLoop(is_running=True) def quit(): mainloop.quit() def sigterm_cb(): gobject.idle_add(quit) t = MonitorThread() t.start() print "Enter mainloop..." while mainloop.is_running(): try: mainloop.run() except KeyboardInterrupt: quit() if __name__ == '__main__': main() 

The program displays only "Watchdog running ... Enter mainloop ..", then nothing. It seems that the thread never starts after entering mainloop.

+6
python multithreading pygtk
source share
2 answers

Can you post the code? You may have problems with Global Interpreter Lock .

Your problem has been solved by someone else :) . I could copy-paste the article here, but in short the gtk ct threads ran into Python threads. You need to disable c-threads by calling gobject.threads_init (), and everything should be fine.

+9
source share

You were unable to initialize code paths based on threads in gtk.

You should remember two things when using streams with PyGTK:

  • GTK themes must be initialized with gtk.gdk.threads_init:

From http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html , copyright is fully reserved by the author. This copyright notice should not be removed.

You can think of glib / gobject instead of pygtk, it is the same.

+2
source share

All Articles