python中的Lock、RLock、Condition与Semaphore详解

Python中的Lock

Lock是Python中最基础的同步原语,属于互斥锁,同一时刻只能有一个线程获取锁。其他线程必须等待锁释放后才能尝试获取。常用于保护共享资源。

import threading

lock = threading.Lock()
shared_resource = 0

def increment():
    global shared_resource
    lock.acquire()
    try:
        shared_resource += 1
    finally:
        lock.release()

threads = []
for _ in range(10):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print(shared_resource)  # 输出10

Lock必须显式地调用release()来释放,否则会导致死锁。建议使用with语句自动管理锁的获取和释放:

def increment_with():
    global shared_resource
    with lock:
        shared_resource += 1

RLock 基本概念

RLock(可重入锁)是 Python 中 threading 模块提供的一种锁机制,允许同一个线程多次获取同一把锁而不被阻塞。与普通锁(Lock)不同,RLock 会记录持有锁的线程和递归层级,避免同一线程重复获取锁时发生死锁。

RLock 使用示例

以下是一个简单的 RLock 示例,展示如何在同一线程中多次获取和释放锁:

import threading

# 创建 RLock 对象
rlock = threading.RLock()

def recursive_func(count):
    # 第一次获取锁
    rlock.acquire()
    print(f"线程 {
     
     threading.current_thread().name

你可能感兴趣的:(python中的Lock、RLock、Condition与Semaphore详解)