1

目标是分配一个线程并等待回调。单线程将永远运行 while 循环。这里的困难在于我们不是直接调用或控制回调,而且我们事先不知道远程服务器调用回调需要多长时间。

我试图在asyncio模块中使用asyncio.Future但未成功寻找解决方案。

from a_module import Server  # <a_module> is fictitious
import random
import time


class App(Server):
    def __init__(self):
        self.response = None

    def send_requests(self):
        """Send request to remote server"""
        self.send_number_to_server(42)  # inherited from Server

        # This is going to loop forever. We should "suspend" the 
        # current thread, allocate a new thread to wait for the
        # callback and then comeback here to return the (not None) 
        # response.
        while self.response is None:
            # Wait for the callback before terminating this method.
            time.sleep(1)  # seconds
        return self.response


    def callback(self, message):
        """Inherited form parent class 'Server'. When the request sent
        with App.send_req has been processed by the remote server,
        this function is invoked in the background."""
        self.response = message


if __name__ == '__main__':
    app = App()
    response = app.send_requests()
    print(response)
4

1 回答 1

1

由于callback是“在后台调用”,Server因此可能已经在运行后台线程。在这种情况下,您希望主线程运行事件循环,并且服务器的后台线程在完成时通知您。假设send_number_to_server没有阻塞,你可以这样做:

class App(Server):
    def __init__(self):
        self._loop = asyncio.get_event_loop()

    async def send_requests(self):
        self.send_number_to_server(42)
        self._future_resp = asyncio.Future()
        resp = await self._future_resp
        self._future_resp = None
        return resp

    def callback(self, message):
        # called from a different thread
        self._loop.call_soon_threadsafe(self._future_resp.set_result, message)

async def main():
    app = App()
    response = await app.send_requests()
    print(response)

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())
于 2018-02-16T23:21:34.073 回答