首页 > 解决方案 > Python线程 - 如何等待来自多个发件人的数据合并结果?

问题描述

我的 ImageStitcher 类正在接收来自不同线程的多个图像消息。然后另一个线程将调用 get_stichted_image() 并且这有效。但它看起来并不好,似乎有点慢。

有没有更好的方法来处理来自不同线程的多个传入消息并等待所有队列(或其他东西)包含一些东西?

class ImageStitcher:
    def __init__(foo):
        self.image_storage = {
            Position.top: queue.Queue(maxsize=1),
            Position.bottom: queue.Queue(maxsize=1)
        }
        foo.register(image_callback)

    # will be called from different threads
    def image_callback(self, image_msg):
        if self.image_storage[image_msg["position"]].full():
            self.image_storage[image_msg["position"].get()
        self.image_storage[image_msg["position"].put(image_msg)

    def get_stichted_image(self):
        try:
            # the following code is ugly and seems to be slow
            top_image_msg = self.image_storage[Position.top].get(timeout=0.1)
            bottom_image_msg = self.image_storage[Position.bottom].get(timeout=0.1)
            return self.stitch_images(top_image_msg, bottom_image_msg)
        except queue.Empty:
            return None

标签: pythonmultithreadingdesign-patternsqueuepython-multithreading

解决方案


推荐阅读