简体   繁体   中英

Terminating main thread from child thread

I have a GUI thread and Main thread. After closing a window I have method called inside the GUI thread. I would like to propagate this to Main thread to end its work. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM