Python、线程和gobject
我正在用pygtk框架写一个程序。这个程序主要做以下几件事:
- 创建一个监控线程来监视某些资源
- 创建一个客户端,从套接字接收数据
- 调用
gobject.Mainloop()
但是,似乎在我的程序进入主循环后,监控线程也不运行了。
我现在的解决办法是使用 gobject.timeout_add
来运行监控的功能。
但我想知道,为什么创建另一个线程不管用呢?
这是我的代码:
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()
程序的输出只有“监控线程正在运行...进入主循环..”,然后就没有其他输出了。看起来线程在进入主循环后就没再运行了。
2 个回答
2
你没有正确初始化基于线程的代码路径在gtk中。
在使用线程和PyGTK时,你需要记住两件事:
- GTK线程必须通过gtk.gdk.threads_init来初始化:
来自 http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html,版权完全保留给作者。这个版权声明不能被删除。
你可以把glib/gobject看作是pygtk,它们是一样的东西。
9
你能发一些代码吗?可能是你遇到了 全局解释器锁 的问题。
这个问题已经被别人解决过了 :)。我可以把文章复制粘贴过来,但简单来说,gtk的C语言线程和Python线程会发生冲突。你需要通过调用 gobject.threads_init() 来禁用C语言线程,这样一切就应该没问题了。