Search code examples
pythonpython-3.xpygobject

Terminate GObject.Mainloop() threads together with main


I have the following two threads:

myThread = threading.Thread(target=sender.mainloop.run, daemon=True)
myThread.start()

myThread2 = threading.Thread(target=receiver.mainloop.run, daemon=True)
myThread2.start()

The targets are GObject.Mainloop() methods. Afterwards my main program is in an infinite loop.

My problem is that when the execution is terminated by CTRL-C, Keyboardexception is raised for both threads, but the main program does not terminate.

Any ideas how could both the main program and the two threads be terminated by CTRL-C?


Solution

  • ctrl-c issues a SIGINT signal, which you can capture in your main thread for a callback. You can then run whatever shutdown code you want in the callback, maybe a sender/receiver.mainloop.quit() or something.

    import threading                                                                                                      
    import signal
    import sys 
    
    def loop():
      while True:
        pass
    
    def exit(signal, frame):
      sys.exit(0)
    
    myThread = threading.Thread(target=loop)
    myThread.daemon = True
    myThread.start()
    
    myThread2 = threading.Thread(target=loop)
    myThread2.daemon = True
    myThread2.start()
    
    signal.signal(signal.SIGINT, exit)
    
    loop()