线程同步技术,目的是为了防止多个线程争抢资源。典型的案例是银行取钱。本文只介绍两种最常用的同步技术,其他的诸如RLock(可重入锁)、Condition(条件变量)、Event(事件)、Barrier(屏障)等
- 互斥锁(Lock)
- 信号量(Semaphore)
互斥锁
官方文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import threading
counter = 0
lock = threading.Lock()
def increment(): global counter for _ in range(300000): with lock: counter += 1
t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment) t1.start() t2.start() t1.join() t2.join()
|
信号量(Semaphore)
官方文档
限制同时访问的线程数量
1 2 3 4 5 6 7 8 9
| semaphore = threading.Semaphore(3)
def access_resource(): with semaphore: print(f"{threading.current_thread().name} 正在访问资源") time.sleep(1)
for i in range(5): threading.Thread(target=access_resource, name=f"Thread-{i}").start()
|