Python中的`threading.Condition`与`threading.Event`有何区别?请分别举例说明它们的典型应用场景。

threading.Condition和threading.Event是Python中用于线程同步的两个工具,虽然它们都可以用于线程间的通信和同步,但各自的设计目标和应用场景有所不同。

1. threading.Condition

threading.Condition是一个复杂的同步原语,它基于锁(通常是threading.Lock或threading.RLock)构建,并提供了额外的等待/通知机制。它适用于多个线程需要在某些条件满足时才能继续执行的场景。

典型应用场景

Condition通常用于生产者-消费者模型,其中生产者线程需要等待消费者线程处理完数据后才能继续生产,反之亦然。

示例

import threading

class ProducerConsumer:
    def __init__(self):
        self.buffer = []
        self.max_size = 5
        self.condition = threading.Condition()

    def produce(self, item):
        with self.condition:
            while len(self.buffer) == self.max_size:
                self.condition.wait()  # 等待缓冲区有空位
            self.buffer.append(item)
            print(f"Produced {item}, buffer: {self.buffer}")
            self.condition.notify()  # 通知消费者线程

    def consume(self):
        with self.condition:
            while not self.buffer:
                self.condition.wait()  # 等待缓冲区有数据
            item = self.buffer.pop(0)
            print(f"Consumed {item}, buffer: {self.buffer}")
            self.condition.notify()  # 通知生产者线程

# 测试
pc = ProducerConsumer()
producer = threading.Thread(target=lambda: [pc.produce(i) for i in range(10)])
consumer = threading.Thread(target=lambda: [pc.consume() for _ in range(10)])
producer.start()
consumer.start()
producer.join()
consumer.join()

2. threading.Event

threading.Event是一个简单的同步机制,它通过一个内部标志(True或False)来表示某个事件是否发生。线程可以通过wait()方法阻塞等待事件被设置,而其他线程可以通过set()方法来触发事件。

典型应用场景

Event适用于需要一次性通知多个线程的场景。例如,多个线程等待服务器启动完成后才开始工作。

示例

import threading
import time

class Server:
    def __init__(self):
        self.event = threading.Event()

    def start(self):
        print("Server is starting...")
        time.sleep(3)  # 模拟启动时间
        print("Server is ready!")
        self.event.set()  # 设置事件标志为True

    def request_handler(self, thread_id):
        print(f"Thread {thread_id} is waiting for server...")
        self.event.wait()  # 等待事件被设置
        print(f"Thread {thread_id} is processing request.")

# 测试
server = Server()
threads = []
for i in range(3):
    t = threading.Thread(target=server.request_handler, args=(i,))
    threads.append(t)
    t.start()

# 启动服务器
server.start()
for t in threads:
    t.join()

总结

  • **Condition**适用于复杂的条件等待场景,可以精确控制哪些线程会被唤醒。
  • **Event**适用于简单的全局事件通知,所有等待线程都会被唤醒。
  • 选择依据:如果需要基于特定条件的同步,使用Condition;如果只是需要一次性通知多个线程,使用Event。