python多线程

71 阅读2分钟

1. 锁(Lock)

锁是最基本的同步原语,用于确保某段代码在同一时间只能被一个线程执行。锁有两种状态:锁定和未锁定。

示例代码

python复制
import threading

lock = threading.Lock()

def critical_section():
    with lock:
        # 这段代码在同一时间只能被一个线程执行
        print(f"Thread {threading.current_thread().name} is in the critical section")

threads = []
for i in range(5):
    t = threading.Thread(target=critical_section)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

2. 可重入锁(RLock)

可重入锁(RLock)允许同一个线程多次获取锁,而不会导致死锁。这在递归调用中非常有用。

示例代码

python复制
import threading

rlock = threading.RLock()

def recursive_function(n):
    with rlock:
        if n > 0:
            print(f"Thread {threading.current_thread().name} is in the recursive function with n={n}")
            recursive_function(n - 1)

threads = []
for i in range(5):
    t = threading.Thread(target=recursive_function, args=(3,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

3. 信号量(Semaphore)

信号量用于控制对共享资源的访问,允许多个线程同时访问。信号量有一个计数器,表示当前可用的资源数量。

示例代码

python复制
import threading

semaphore = threading.Semaphore(3)  # 允许最多3个线程同时访问

def access_resource():
    with semaphore:
        print(f"Thread {threading.current_thread().name} is accessing the resource")
        threading.Event().wait(1)  # 模拟资源访问

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

for t in threads:
    t.join()

4. 事件(Event)

事件用于线程之间的通信。一个线程可以等待事件的发生,而另一个线程可以设置事件。

示例代码

python复制
import threading

event = threading.Event()

def wait_for_event():
    print(f"Thread {threading.current_thread().name} is waiting for the event")
    event.wait()
    print(f"Thread {threading.current_thread().name} received the event")

def set_event():
    threading.Event().wait(2)  # 模拟一些工作
    print(f"Thread {threading.current_thread().name} is setting the event")
    event.set()

threads = []
for i in range(3):
    t = threading.Thread(target=wait_for_event)
    threads.append(t)
    t.start()

setter_thread = threading.Thread(target=set_event)
setter_thread.start()

for t in threads:
    t.join()
setter_thread.join()

5. 条件变量(Condition)

条件变量用于复杂的线程间同步,允许线程等待某个条件的发生,并在条件满足时被唤醒。

示例代码

python复制
import threading

condition = threading.Condition()
shared_resource = []

def producer():
    with condition:
        for i in range(5):
            shared_resource.append(i)
            print(f"Producer added {i}")
            condition.notify()  # 通知消费者
            threading.Event().wait(1)  # 模拟生产时间

def consumer():
    with condition:
        while True:
            condition.wait()  # 等待生产者的通知
            if shared_resource:
                item = shared_resource.pop(0)
                print(f"Consumer consumed {item}")
            else:
                break

producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)

producer_thread.start()
consumer_thread.start()

producer_thread.join()
consumer_thread.join()