目标是分配一个线程并等待回调。单线程将永远运行 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)