2011-05-23 139 views
7

我想玩與PyGTK的線程錯誤。我到目前爲止的代碼如下:PyGTK阻止非GUI線程

#!/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() 

它確實NonGUIThreads連續運行3秒。之後,顯示窗口和其他線程停止!關閉窗口後,線程再次運行。

gtk.main()怎麼可能阻塞其他線程?線程不依賴於任何鎖,因此它們應該在顯示窗口期間工作。

回答

5

您必須先撥打gobject.threads_init(),然後才能執行任何與Gtk相關的操作。

More info in PyGtk's FAQ

+0

感謝您的回答!我發現那個頁面,但我認爲這只是針對線程想要與GTK進行通信的情況。我錯了。 – izidor 2011-05-24 05:32:49