PyGTK 阻塞非 GUI 线程
我想用 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()
怎么可能阻塞其他线程?这些线程不依赖于任何锁,因此它们应该在显示窗口期间工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在执行任何与 Gtk 相关的操作之前,您必须调用
gobject.threads_init()
。更多信息请参见 PyGtk 的常见问题解答
You have to call
gobject.threads_init()
before you do anything Gtk related.More info in PyGtk's FAQ