vendredi 30 octobre 2020

Python threading - How to wait for data from multiple senders to merge the result?

My ImageStitcher class is receiving multiple image messages from different threads. Another thread will then call the get_stichted_image() and this works. But it doesn't look good and seems kinda slow.

Is there a better way to handle multiple incoming messages from different threads and wait for all queues (or something else) to contain something?

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:
            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

Aucun commentaire:

Enregistrer un commentaire