Python, thread and gobject

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-03 10:43:08

问题


I am writing a program by a framework using pygtk. The main program doing the following things:

  1. Create a watchdog thread to monitor some resource
  2. Create a client to receive data from socket
  3. 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.


回答1:


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.




回答2:


You have failed to initialise the threading-based code-paths in gtk.

You must remember two things when using threads with PyGTK:

  1. GTK Threads must be initialised with gtk.gdk.threads_init:

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.



来源:https://stackoverflow.com/questions/1796588/python-thread-and-gobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!