我想玩PyGTK的线程错误。到目前为止我有这个代码:
#!/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()
如何能够阻止其他线程?线程不依赖于任何锁定,因此它们应该在窗口显示时工作。