Python3异步-add_done_callback的回调不更新服务器类中的自变量

时间:2018-11-05 21:00:11

标签: python python-3.5 python-asyncio

我有两个用asyncio.start_server创建的服务器: asyncio.start_server(self.handle_connection, host = host, port = port)并循环运行:

loop.run_until_complete(asyncio.gather(server1, server2))
loop.run_forever()

我正在使用asyncio.Queue在服务器之间进行通信。通过queue.put(msg)添加的来自Server2的消息被Server1中的queue.get()接收成功。我正在运行queue.get()的{​​{1}}并将其用作回调 来自Server1的asyncio.ensure_future方法:

add_done_callback

但是此def callback(self, future): msg = future.result() self.msg = msg 无法正常工作-self.msg不会更新。我在做什么错了?

已更新 带有附加代码以显示最大完整示例:

callback

服务器类:

class Queue(object):

    def __init__(self, loop, maxsize: int):
        self.instance = asyncio.Queue(loop = loop, maxsize = maxsize)

    async def put(self, data):
        await self.instance.put(data)

    async def get(self):
        data = await self.instance.get()
        self.instance.task_done()
        return data

    @staticmethod
    def get_instance():
        return Queue(loop = asyncio.get_event_loop(), maxsize = 10)

下一步,我正在运行服务器:

    class BaseServer(object):

        def __init__(self, host, port):
            self.instance = asyncio.start_server(self.handle_connection, host = host, port = port)

        async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
            pass

        def get_instance(self):
            return self.instance

        @staticmethod
        def create():
            return BaseServer(None, None)

在server2的loop.run_until_complete(asyncio.gather(server1.get_instance(), server2.get_instance())) loop.run_forever() 中,我呼叫handle_connection,在server1的queue.put(msg)中,我注册handle_connection作为任务:

queue.get()

server1的 task_queue = asyncio.ensure_future(queue.get()) task_queue.add_done_callback(self.process_queue) 方法:

process_queue

server1的 def process_queue(self, future): msg = future.result() self.msg = msg 方法:

handle_connection

尽管完成了 async def handle_connection(self, reader: StreamReader, writer: StreamWriter): task_queue = asyncio.ensure_future(queue.get()) task_queue.add_done_callback(self.process_queue) while self.msg != SPECIAL_VALUE: # doing something ,但称为task_queue的{​​{1}}从未更新。

1 个答案:

答案 0 :(得分:3)

基本上,当您使用异步结构时,我认为您可以直接等待结果:

async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
    msg = await queue.get()
    process_queue(msg)  # change it to accept real value instead of a future.
    # do something