'How to return consumer result back to producer in python?

Imagine the following consumer tread class :

import struct
import serial

QUEUE_SIZE = 16
msg_queue = Queue.Queue(self.QUEUE_SIZE) # Lets use tuples as input "tuple(msg, callBack)", tuples are immutable

class MsgConsumer(threading.Thread, client):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
        super().__init__()
        self.target = target
        self.name = name
        return

    def run(self):
        while True:
            if not msg_queue.empty():
                msg = msg_queue.get()[0]            # access the msg from the tuple
                resp = client.query(msg)            # do the request of the msg
                result = msg_queue.get()[1](resp)   # access the response interpreter lambda from the tuple and and give the response as argument to it to get the result
                # ;-( "result" is needed in the getx/y/z functions
        return

# functions to put messages into the queue, but how to get the result back ?
def getx():
    msg = createMsgForX()
    resp_interpreter = lambda resp : int.from_bytes(resp.payload[0:2], "little") if resp else None
    msg_queue.put(tuple(msg, resp_interpreter))
    # ... how to get the value

def gety():
    msg = createMsgForY()
    resp_interpreter = lambda resp : int.from_bytes(resp.payload, "little") if resp else None
    msg_queue.put(tuple(msg, resp_interpreter))
    # ... how to get the value

def getz():
    msg = createMsgForZ()
    resp_interpreter = lambda resp : int.from_bytes(resp.payload, "little") if resp else None
    msg_queue.put(tuple(msg, resp_interpreter))
    # ... how to get the value


if __name__ == "__main__":
    msg_c = MsgConsumer(name='msg_consumer', client = my_protocol_client)
    msg_consumer.start()

    how_to_get_X = getX()
    how_to_get_Y = getY()
    how_to_get_Z = getZ()

Could someone tell me how to get the result of x/y/z back? (In reality, these are 1000 functions not only x/y/z)

The client is the implementation of an unknown protocol. And the getx/y/z functions are examples of how to get a specific value from the serial interface via this protocol.

I can only think of one solution to this problem.

  1. Add a global variable that is filled with the "result" from the lambda and add a lock to this variable

Is there a more pythonic way to solve this? Maybe via futures.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source