简体   繁体   English

从子线程终止主线程

[英]Terminating main thread from child thread

I have a GUI thread and Main thread. 我有一个GUI线程和主线程。 After closing a window I have method called inside the GUI thread. 关闭窗口后,我在GUI线程内调用了方法。 I would like to propagate this to Main thread to end its work. 我想将此传播到Main线程以结束其工作。 Main thread is doing several steps, so I am able to set stop_event, but I do not want to check after each line of code for Main thread if stop_event is set. 主线程正在执行几个步骤,因此我可以设置stop_event,但是我不想在每行代码之后检查主线程是否设置了stop_event。

Thank you for your advices. 感谢您的建议。

If your purpose is just to terminate main thread from the child thread, try the below. 如果您的目的只是终止子线程的主线程,请尝试以下操作。

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