Python 中的线程安全
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
其他同步原语:
- RLock:可重入锁,同一线程可多次 acquire
- Semaphore:信号量,限制同时访问的线程数
- Event:线程间事件通知
- Condition:条件变量,复杂的线程同步
- Barrier:屏障,等待所有线程到达
- Queue:线程安全的队列(
queue.Queue)
Python 中 threading 模块还提供 Timer、ThreadLocal 等工具。