Python双线程互相控制示例
Python双线程互相控制示例
Code
import time import pynput import threading # 用于控制循环和监听的全局变量 running = True def on_press(key): global running try: if key == pynput.keyboard.Key.esc: running = False except AttributeError: pass def on_release(key): # 停止监听 if key == pynput.keyboard.Key.esc: return False def print_loop(): global running for i in range(1000): if not running: break print(i) time.sleep(0.000001) print("Loop finished or stopped by ESC.") # 循环结束后,设置running为False以停止键盘监听 running = False def listen_keyboard(): global running with pynput.keyboard.Listener(on_press=on_press, on_release=on_release) as listener: while running: listener.join() def main(): # 创建线程 thread1 = threading.Thread(target=listen_keyboard) thread2 = threading.Thread(target=print_loop) # 启动线程 thread1.start() thread2.start() # 等待线程结束 thread1.join() thread2.join() if __name__ == '__main__': start_time = time.time() main() end_time = time.time() dur = end_time - start_time print('脚本运行时间是:{:.2f}秒'.format(dur))