006Python-threading__2

线程同步技术,目的是为了防止多个线程争抢资源。典型的案例是银行取钱。本文只介绍两种最常用的同步技术,其他的诸如RLock(可重入锁)、Condition(条件变量)、Event(事件)、Barrier(屏障)等

  1. 互斥锁(Lock)
  2. 信号量(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)  # 最多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()

006Python-threading__2
https://jackiedai.github.io/2025/03/19/011Python/008Python-threading2/
Author
lingXiao
Posted on
March 19, 2025
Licensed under