Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyGTK blocking non-GUI threads

I want to play with the thread-bugs with PyGTK. I have this code so far:

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
import threading
from time import sleep

class SomeNonGUIThread(threading.Thread):
    def __init__(self, tid):
        super(SomeNonGUIThread, self).__init__()
        self.tid = tid

    def run(self):
        while True:
            print "Client #%d" % self.tid
            sleep(0.5)

class App(threading.Thread):
    def __init__(self):
        super(App, self).__init__()

        self.window = gtk.Window()
        self.window.set_size_request(300, 300)
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.connect('destroy', gtk.main_quit)

        self.window.show_all()

    def run(self):
        print "Main start"
        gtk.main()
        print "Main end"


if __name__ == "__main__":
    app = App()

    threads = []
    for i in range(5):
        t = SomeNonGUIThread(i)
        threads.append(t)

    # Ready, set, go!
    for t in threads:
        t.start()

    # Threads work so well so far
    sleep(3)

    # And now, they freeze :-(
    app.start()

It does that NonGUIThreads are running for 3 seconds concurently. Afterwards, the window is shown and other threads are stoped! After closing the window, threads are running again.

How it is possible, that gtk.main() is able to block other threads? The threads do not depend on any lock, so they should work during the window is shown.

like image 904
izidor Avatar asked May 23 '11 18:05

izidor


1 Answers

You have to call gobject.threads_init() before you do anything Gtk related.

More info in PyGtk's FAQ

like image 185
eduffy Avatar answered Sep 24 '22 02:09

eduffy