Python、线程和gobject [英] Python, thread and gobject
问题描述
我正在使用 pygtk 通过框架编写程序.主程序做了以下几件事:
I am writing a program by a framework using pygtk. The main program doing the following things:
- 创建一个看门狗线程来监控一些资源
- 创建一个客户端来接收来自套接字的数据
- 调用
gobject.Mainloop()
但是好像我的程序进入Mainloop后,看门狗线程也跑不起来了.
but it seems after my program enter the Mainloop, the watchdog thread also won't run.
我的解决方法是使用 gobject.timeout_add
来运行监视器.
My workaround is to use gobject.timeout_add
to run the monitor thing.
但是为什么创建另一个线程不起作用?
But why does creating another thread not work?
这是我的代码:
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()
程序只输出Watchdog running...Enter mainloop...",然后什么都没有.进入主循环后似乎线程永远不会运行.
The program output only "Watchdog running...Enter mainloop..", then nothing. Seems thread never run after entering mainloop.
推荐答案
你能贴出一些代码吗?可能是您在使用 全局解释器锁 时遇到问题.
Can you post some code? It could be that you have problems with the Global Interpreter Lock.
您的问题已由他人解决 :).我可以在这里复制粘贴这篇文章,但简而言之,gtk 的 c 线程与 Python 线程发生冲突.您需要通过调用 gobject.threads_init() 来禁用 c 线程,并且所有应该没问题.
Your problem solved by someone else :). I could copy-paste the article here, but in short gtk's c-threads clash with Python threads. You need to disable c-threads by calling gobject.threads_init() and all should be fine.
这篇关于Python、线程和gobject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!