MST

星途 面试题库

面试题:Python中Condition同步原语的复杂应用场景

假设你有一个生产者 - 消费者模型,生产者线程生产数据并放入队列,消费者线程从队列中取出数据处理。使用`Condition`同步原语来实现这个模型,需要处理队列满和队列空的情况,阐述实现思路并给出关键代码片段。
49.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建一个共享队列用于存储数据。
  2. 使用 Condition 对象来协调生产者和消费者线程之间的同步。
  3. 生产者线程在向队列中放入数据前,先检查队列是否已满。如果已满,调用 condition.wait() 等待,直到队列有空间。放入数据后,调用 condition.notify() 唤醒等待的消费者线程。
  4. 消费者线程在从队列中取出数据前,先检查队列是否为空。如果为空,调用 condition.wait() 等待,直到队列中有数据。取出数据后,调用 condition.notify() 唤醒等待的生产者线程。

关键代码片段

import threading
import queue


class ProducerConsumer:
    def __init__(self, capacity):
        self.queue = queue.Queue(capacity)
        self.condition = threading.Condition()

    def producer(self, item):
        with self.condition:
            while self.queue.full():
                self.condition.wait()
            self.queue.put(item)
            print(f"Produced: {item}")
            self.condition.notify()

    def consumer(self):
        with self.condition:
            while self.queue.empty():
                self.condition.wait()
            item = self.queue.get()
            print(f"Consumed: {item}")
            self.condition.notify()

可以这样使用上述代码:

# 创建生产者 - 消费者实例,队列容量为 5
pc = ProducerConsumer(5)

# 模拟生产者生产数据
producer_thread = threading.Thread(target=pc.producer, args=(1,))
producer_thread.start()

# 模拟消费者消费数据
consumer_thread = threading.Thread(target=pc.consumer)
consumer_thread.start()

producer_thread.join()
consumer_thread.join()

上述代码中,ProducerConsumer 类封装了生产者 - 消费者模型的逻辑。producer 方法负责生产数据并放入队列,consumer 方法负责从队列中取出数据并处理。Condition 用于在队列满或空时协调线程的等待与唤醒。