CodeWalk

Python 中的线程安全

作者:Yahuda · 2026-05-30 12:55

Python 中如何使用 Lock 实现线程安全?还有哪些同步原语(threading 模块)?

回答

Yahuda

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:  # 自动 acquire 和 release
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(counter)  # 1000000

其他同步原语

  1. RLock:可重入锁,同一线程可多次 acquire
  2. Semaphore:信号量,限制同时访问的线程数
  3. Event:线程间事件通知
  4. Condition:条件变量,复杂的线程同步
  5. Barrier:屏障,等待所有线程到达
  6. Queue:线程安全的队列(queue.Queue

Python 中 threading 模块还提供 TimerThreadLocal 等工具。