Python 多线程同步机制包括 Lock、Condition、Event、Queue,用于控制线程执行顺序。
同步机制对比
| 机制 | 特点 | 适用场景 |
|---|
| Lock | 互斥访问 | 保护临界区 |
| Condition | 条件等待 | 生产者-消费者 |
| Event | 信号通知 | 线程启停控制 |
| Queue | FIFO 任务队列 | 任务分发 |
Lock(锁)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| import threading
lock = threading.Lock()
def worker(name, order):
with lock:
order.append(name)
threads = []
order = []
for i in range(5):
t = threading.Thread(target=worker, args=(i, order))
threads.append(t)
t.start()
for t in threads:
t.join()
|
Condition(条件变量)
1
2
3
4
5
6
7
8
9
10
11
12
13
| import threading
condition = threading.Condition()
current = 0
def worker(name, order):
global current
with condition:
while name != current:
condition.wait()
order.append(name)
current += 1
condition.notify_all()
|
Event(事件)
1
2
3
4
5
6
7
8
9
10
11
| import threading
start_event = threading.Event()
def worker(name, order):
start_event.wait()
order.append(name)
# 控制线程启动
start_event.set()
start_event.clear()
|
Queue(队列)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| import threading
import queue
task_queue = queue.Queue()
def worker(order):
while True:
name = task_queue.get()
if name is None:
break
order.append(name)
task_queue.task_done()
# 按顺序放入任务
for i in range(5):
task_queue.put(i)
task_queue.join()
|
选择指南
- Lock:简单互斥,一次一个线程
- Condition:需要等待条件满足
- Event:线程启停、广播通知
- Queue:任务队列、生产者-消费者
Comments