本文整理 Python 多執行緒核心模組 thread(低階)、threading(高階)與 queue(執行緒安全佇列)的用法,並提供完整範例說明啟動、同步與資料傳遞。
| 模組 | 特點 |
|---|---|
thread | 低階 API,提供 start_new_thread、allocate_lock,適合簡單腳本 |
threading | 物件導向,Thread、Lock、RLock、Condition、Event 等,功能豐富 |
queue | 執行緒安全佇列 Queue,支援 put/get 阻塞,適合生產者-消費者模型 |
import thread, time
def worker(no, interval):
for i in range(5):
print(f"Thread-{no} sleep {interval}s, time: {time.ctime()}")
time.sleep(interval)
print(f"Thread-{no} finished")
thread.start_new_thread(worker, (1, 2))
thread.start_new_thread(worker, (2, 1))
time.sleep(10) # 主執行緒等待
import threading, time, random
locks = []
for _ in range(2):
lock = threading.Lock()
lock.acquire()
locks.append(lock)
def task(n, sec, lock):
print(f"Thread {n} start, sleep {sec}s")
time.sleep(sec)
print(f"Thread {n} end")
lock.release()
threads = []
for i, lock in enumerate(locks):
t = threading.Thread(target=task, args=(i, random.choice([2,4]), lock))
t.start()
threads.append(t)
for lock in locks:
while lock.locked(): pass # 等待釋放
print("All threads done")
import threading, queue, time, random
q = queue.Queue(maxsize=5)
def producer():
for i in range(10):
q.put(i)
print(f"Produced {i}")
time.sleep(random.random())
def consumer():
while True:
item = q.get()
print(f"Consumed {item}")
q.task_done()
time.sleep(random.random())
threading.Thread(target=producer).start()
threading.Thread(target=consumer, daemon=True).start()
q.join()
print("Done")
join() 或鎖機制等待。thread 模組在 Python 3 中改名為 _thread,建議直接使用 threading。queue.Queue 避免競爭條件。