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