Python threading模块锁原语详解

📅 2026/6/17 12:53:16
Python threading模块锁原语详解
Python threading模块的锁原语threading模块提供多种锁Lock、RLock、Semaphore、Event、Condition、Barrier。Lock的基本使用import threadinglock threading.Lock()shared_counter 0def increment():global shared_counterfor _ in range(100000):lock.acquire()shared_counter 1lock.release()threads [threading.Thread(targetincrement) for _ in range(10)]for t in threads: t.start()for t in threads: t.join()print(shared_counter) # 1000000acquire/release保护临界区。with lock更安全。with lock的异常安全lock threading.Lock()with lock:shared_counter 1with语句自动处理acquire和release。异常时也确保释放锁。lock.acquire的超时和阻塞控制if lock.acquire(timeout5):try:shared_counter 1finally:lock.release()else:print(Failed to acquire lock within 5 seconds)timeout0时非阻塞尝试。timeout0等特指定毫秒数。RLock可重入锁lock threading.RLock()def recursive(n):if n 0:returnwith lock:print(fn{n}, recurse_depth{n})recursive(n - 1)recursive(5) # 正常执行RLock允许同一线程多次获取。递归锁计数器跟踪获取次数每次release减少。Semaphore限制并发sem threading.Semaphore(3)def limited_task():with sem:print(fTask running, active{threading.active_count()})time.sleep(1)threads [threading.Thread(targetlimited_task) for _ in range(10)]for t in threads: t.start()BoundedSemaphore防止超量释放sem threading.BoundedSemaphore(3)sem.release() # ValueError: Semaphore released too many timesEvent让一个线程通知其他线程event threading.Event()def waiter():print(Waiting for event...)event.wait()print(Got event!)def setter():time.sleep(2)event.set()print(Event set)threading.Thread(targetwaiter).start()threading.Thread(targetsetter).start()event.wait()阻塞直到event.set()被调用。event.is_set()检查状态。event.clear()重置。Condition变量实现生产者消费者cv threading.Condition()queue []def consumer():with cv:while not queue:cv.wait()item queue.pop(0)print(fConsumed: {item})def producer():with cv:queue.append(item)cv.notify()Barrier同步多个线程def worker(barrier, name):time.sleep(random.random())print(f{name} reached barrier)barrier.wait()print(f{name} passed barrier)barrier threading.Barrier(3)threads [threading.Thread(targetworker, args(barrier, i)) for i in range(3)]for t in threads: t.start()Barrier(3)等待3个线程到达后同时释放。