Python、线程和 gobject
我正在使用 pygtk 通过框架编写程序。主程序执行以下操作:
- 创建一个看门狗线程来监视某些资源
- 创建一个客户端以从套接字
- 调用
gobject.Mainloop()
接收数据,但似乎在我的程序进入 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()
程序仅输出“Watchdog running...Enter mainloop..”,然后什么也没有。 似乎线程在进入主循环后永远不会运行。
I am writing a program by a framework using pygtk. The main program doing the following things:
- Create a watchdog thread to monitor some resource
- Create a client to receive data from socket
- call
gobject.Mainloop()
but it seems after my program enter the Mainloop, the watchdog thread also won't run.
My workaround is to use gobject.timeout_add
to run the monitor thing.
But why does creating another thread not work?
Here is my code:
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()
The program output only "Watchdog running...Enter mainloop..", then nothing.
Seems thread never run after entering mainloop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你能发布一些代码吗?可能是您的全局解释器锁有问题。
您的问题已由其他人解决了:)。我可以在这里复制粘贴这篇文章,但简而言之,gtk 的 C 线程与 Python 线程发生冲突。您需要通过调用 gobject.threads_init() 来禁用 C 线程,并且一切都应该没问题。
Can you post some code? It could be that you have problems with the Global Interpreter Lock.
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.
您未能在 gtk 中初始化基于线程的代码路径。
来自 http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html,版权完全归作者所有。不得删除此版权声明。
你可以认为 glib/gobject 而不是 pygtk,它是一样的东西。
You have failed to initialise the threading-based code-paths in gtk.
From http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html, copyright entirely retained by author. This copyright notice must not be removed.
You can think glib/gobject instead of pygtk, it's the same thing.