簡體   English   中英

從子線程終止主線程

[英]Terminating main thread from child thread

我有一個GUI線程和主線程。 關閉窗口后,我在GUI線程內調用了方法。 我想將此傳播到Main線程以結束其工作。 主線程正在執行幾個步驟,因此我可以設置stop_event,但是我不想在每行代碼之后檢查主線程是否設置了stop_event。

感謝您的建議。

如果您的目的只是終止子線程的主線程,請嘗試以下操作。

import threading
import signal
import time
import os


def main():
    threading.Thread(target=child).start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt as e:
        # KeyboardInterrupt happens by `signal.SIGINT` from the child thread.
        print('Main thread handle something before it exits')
    print('End main')

def child():
    print('Run child')
    time.sleep(2)
    # Send a signal `signal.SIGINT` to main thread.
    # The signal only head for main thread.
    os.kill(os.getpid(), signal.SIGINT)
    print('End child')


if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM