【问题标题】:Terminate GObject.Mainloop() threads together with main与 main 一起终止 GObject.Mainloop() 线程
【发布时间】:2016-08-09 09:43:30
【问题描述】:

我有以下两个线程:

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

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

目标是 GObject.Mainloop() 方法。 之后我的主程序陷入了无限循环。

我的问题是当执行被CTRL-C终止时,两个线程都会引发Keyboardexception,但主程序并没有终止。

你知道主程序和两个线程如何被 CTRL-C 终止吗?

【问题讨论】:

    标签: python python-3.x pygobject


    【解决方案1】:

    ctrl-c 发出一个 SIGINT 信号,您可以在主线程中捕获该信号以进行回调。然后,您可以在回调中运行您想要的任何关闭代码,可能是sender/receiver.mainloop.quit() 或其他东西。

    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()  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多