Python-主线程控制子线程结束

需求:主线程创建子线程和键盘输入监听线程,然后等待它们退出。当用户输入 'q' 后, 子线程会收到停止信号并退出,键盘输入监听线程也会退出,最终主线程退出。

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.")

 主线程创建子线程和键盘输入监听线程,然后等待它们退出。当用户输入 0 后,子线程会收到停止信号并退出,键盘输入监听线程也会退出,最终主线程退出。

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("主线程退出")

猜你喜欢

转载自blog.csdn.net/Scarlett2025/article/details/132405364
今日推荐