答案:python中线程同步常用Lock、RLock、Condition、Semaphore和Event机制。1. Lock确保同一时间仅一个线程执行代码段,避免共享资源竞争;2. RLock支持同一线程多次加锁,适用于嵌套调用;3. Condition实现线程间协作,常用于生产者-消费者模型;4. Semaphore控制并发访问资源的线程数量;5. Event用于线程通信,通过set和wait触发事件。应根据场景选择合适方式,防止死锁并合理管理锁的粒度与释放。
在Python中使用threading
模块进行多线程编程时,多个线程可能同时访问共享资源,导致数据混乱或结果不可预测。为了解决这个问题,需要实现线程同步。Python提供了多种机制来实现线程同步,以下是常用的几种方式及其使用方法。
1. 使用 Lock(互斥锁)
Lock 是最基本的同步机制,用于确保同一时间只有一个线程可以执行某段代码。
用法说明:
- 调用
lock.acquire()
获取锁,其他线程将阻塞直到锁被释放。 - 执行完临界区代码后,必须调用
lock.release()
释放锁。 - 建议使用
with
语句,避免忘记释放锁。
示例代码:
立即学习“Python免费学习笔记(深入)”;
import threading <h1>创建一个锁</h1><p>lock = threading.Lock() counter = 0</p><p>def increment(): global counter for _ in range(100000): with lock: # 自动获取和释放锁 counter += 1</p><p>t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment)</p><p>t1.start() t2.start()</p><p>t1.join() t2.join()</p><p>print(counter) # 输出:200000</p>
2. 使用 RLock(可重入锁)
RLock 允许同一个线程多次获取同一个锁,而不会造成死锁,适合递归调用或嵌套加锁场景。
与 Lock 的区别:
- Lock 不允许同一线程重复获取,否则会阻塞。
- RLock 可以被同一线程多次 acquire,但 release 次数必须匹配。
示例:
import threading <p>rlock = threading.RLock()</p><p>def outer(): with rlock: print("Outer acquired") inner()</p><p>def inner(): with rlock: print("Inner acquired")</p><p>t = threading.Thread(target=outer) t.start() t.join()</p>
3. 使用 Condition(条件变量)
Condition 用于线程间的协作,比如生产者-消费者模型。它基于 Lock,并提供 wait()、notify() 和 notify_all() 方法。
典型用途:一个线程等待某个条件成立,另一个线程修改状态后通知等待的线程。
示例:生产者-消费者模型
import threading import time import random <p>condition = threading.Condition() items = []</p><p>def producer(): for i in range(5): with condition: item = random.randint(1, 100) items.append(item) print(f"Produced: {item}") condition.notify() # 唤醒一个等待的消费者 time.sleep(1)</p><p>def consumer(): while True: with condition: while not items: condition.wait() # 等待有数据 item = items.pop(0) print(f"Consumed: {item}") if len(items) == 0: break</p><p>t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer)</p><p>t1.start() t2.start()</p><p>t1.join() t2.join()</p>
4. 使用 Semaphore(信号量)
Semaphore 控制同时访问某一资源的线程数量,适用于限制并发数,如数据库连接池。
示例:限制最多两个线程同时运行
import threading import time <p>semaphore = threading.Semaphore(2)</p><p>def worker(name): with semaphore: print(f"{name} is working...") time.sleep(2) print(f"{name} done.")</p><p>threads = [threading.Thread(target=worker, args=(f"Thread-{i}",)) for i in range(5)]</p><p>for t in threads: t.start()</p><p>for t in threads: t.join()</p>
5. 使用 Event(事件)
Event 用于线程间通信,一个线程设置事件,其他线程等待该事件发生。
常用方法: wait()
, set()
, clear()
示例:
import threading import time <p>event = threading.Event()</p><p>def waiter(): print("Waiting for event...") event.wait() print("Event triggered!")</p><p>def setter(): time.sleep(2) print("Setting event") event.set()</p><p>t1 = threading.Thread(target=waiter) t2 = threading.Thread(target=setter)</p><p>t1.start() t2.start()</p><p>t1.join() t2.join()</p>
基本上就这些常见的线程同步方式。根据具体场景选择合适的机制:简单互斥用 Lock,嵌套加锁用 RLock,线程协作用 Condition 或 Event,控制并发数用 Semaphore。关键是避免死锁,注意锁的粒度和释放时机。