Python- the main thread controls the end of the child thread

Requirements: The main thread creates child threads and keyboard input listening threads, and then waits for them to exit. When the user enters 'q', the child thread will receive the stop signal and exit, the keyboard input monitoring thread will also exit, and finally the main thread will exit.

import threading
import time
import keyboard


class WorkerThread(threading.Thread):
    def __init__(self, stop_event):
        super().__init__()
        self.stop_event = stop_event

    def run(self):
        thread_id = threading.get_ident()  # 获取线程 ID
        print(f"Worker thread {thread_id} 已经启动了~")
        while not self.stop_event.is_set():
            print(f"Worker thread {thread_id} 正在运行中~")
            time.sleep(1)
        print(f"Worker thread  {thread_id} 已经停止~")


def key_listener(stop_event):
    lock = threading.Lock()  # 创建互斥锁
    print("Press 'q' to stop the thread...")

    while True:
        if keyboard.is_pressed('q'):
            with lock:  # 使用互斥锁来保护共享资源的访问
                worker_id = worker_thread.ident
                print(f"Stopping worker thread {worker_id}...")
                stop_event.set()
            break


if __name__ == '__main__':
    # 创建线程事件
    stop_event = threading.Event()

    # 创建子线程并传递线程事件
    worker_thread = WorkerThread(stop_event)

    # 创建键盘输入监听线程
    keyboard_thread = threading.Thread(target=key_listener, args=(stop_event,))

    # 启动子线程和键盘输入监听线程
    worker_thread.start()
    keyboard_thread.start()

    # 等待子线程和键盘输入监听线程退出
    worker_thread.join()
    keyboard_thread.join()

    # 主线程退出
    main_thread_id = threading.main_thread().ident
    print(f"Main thread {main_thread_id} exiting.")

 The main thread creates child threads and keyboard input listening threads, and then waits for them to exit. When the user enters 0, the child thread will receive the stop signal and exit, the keyboard input monitoring thread will also exit, and finally the main thread will exit.

import threading
import time


class WorkerThread(threading.Thread):
    def __init__(self, stop_event):
        super().__init__()
        self.stop_event = stop_event

    def run(self):
        while not self.stop_event.is_set():
            print("线程在运行~")
            time.sleep(1)
        print("线程已经结束~")


def key_listen(stop_event):
    while True:
        command = input("请输入指令")
        if command == "0":
            stop_event.set()
            worker_thread.join()
            print("线程已经完全结束~")
            break


if __name__ == '__main__':
    stop_event = threading.Event()
    worker_thread = WorkerThread(stop_event)

    keyboard_thread = threading.Thread(target=key_listen, args=(stop_event,))

    worker_thread.start()
    keyboard_thread.start()

    worker_thread.join()
    keyboard_thread.join()

    print("主线程退出")

Guess you like

Origin blog.csdn.net/Scarlett2025/article/details/132405364