速戰速決 Python - python 標準庫: 多執行緒和執行緒同步
阿新 • • 發佈:2022-01-20
速戰速決 Python - python 標準庫: 多執行緒和執行緒同步
速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd
速戰速決 Python - python 標準庫: 多執行緒和執行緒同步
示例如下:
standardLib/thread.py
# 通過 import threading 實現多執行緒 import threading import time # 繼承 threading.Thread class MyThread(threading.Thread): def __init__(self, threadName): threading.Thread.__init__(self) self.name = threadName # 需要在新開執行緒中執行的邏輯 def run(self): myPrint(self.name + " 開始") temp = 0 start = time.perf_counter() # 獲取裝置開機到現在經過的秒數 while True: if temp < 10: myPrint(self.name + " 執行中") time.sleep(0.2) # 阻塞 0.2 秒 temp += 1 else: break end = time.perf_counter() myPrint(f"{self.name} 運行了 {end-start} {start}秒,退出") # 通過 threading.Lock() 實現執行緒同步 lock = threading.Lock() def myPrint(message): # 獲取鎖 lock.acquire() print(message) # 自己可以測試一下,不用鎖的話列印會比較亂,用了鎖就不會了 # 釋放鎖 lock.release() print("主執行緒開始") # 建立新執行緒 thread1 = MyThread("thread_1") thread2 = MyThread("thread_2") thread3 = MyThread("thread_3") # 啟動新執行緒 thread1.start() thread2.start() thread3.start() # 在當前執行緒等待新開執行緒執行完畢 thread1.join() thread2.join() thread3.join() print("主執行緒退出")
速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd