Python,线程和gobject

Dav*_*uan 6 python multithreading pygtk

我正在使用pygtk通过框架编写程序.主程序做了以下事情:

  1. 创建一个监视程序线程来监视某些资源
  2. 创建一个客户端以从套接字接收数据
  3. 呼叫 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()
Run Code Online (Sandbox Code Playgroud)

程序只输出"Watchdog running ...输入mainloop ..",然后什么都没有.进入mainloop后似乎线程永远不会运行.

ext*_*eon 9

你能发一些代码吗?可能是您遇到Global Interpreter Lock问题.

别人解决了你的问题:).我可以在这里复制粘贴文章,但简而言之,gtk的c-threads与Python线程冲突.你需要通过调用gobject.threads_init()来禁用c线程,所有都应该没问题.

  • 我很高兴你在答案中添加了一个简短的提示,因为链接已经死了. (2认同)