admin管理员组文章数量:1289557
I write a Python program involving a loop of create_task()
that calls async functions. In each task, it waits for another thread to set the result for a Future
object.
async def run(self) -> int:
cur_ts = 0
tasks: List[asyncio.Task] = []
while not self.requests.empty():
req = self.requests.get()
self.num_reqs += 1
t = asyncio.create_task(self._send_request(req))
tasks.append(t)
interval = req.get_timestamp() - cur_ts
cur_ts = req.get_timestamp()
# Sleep for x ms
await asyncio.sleep(interval / 1000)
await asyncio.gather(*tasks)
accuracy = self.num_corrects.get() / self.num_reqs
failure = self.num_failures.get() / self.num_reqs
print("Accuracy is ", accuracy, ", failure rate is ", failure)
return 0
async def _send_request(self, req: Request) -> None:
err = self.sched.receive(req)
if err == 0:
res = await req.get_result()
if res == 1:
self.num_corrects.increment()
else:
self.num_failures.increment()
I encountered a strange problem that before the end of the loop in run()
, when the result is set, _send_request()
can proceed after the await
. But once the loop ends, _send_request()
will be stuck even if the result is set.
The set_result()
and get_result()
in Request
are:
def set_result(self, result: int):
if not self.result.done():
self.result.set_result(result)
async def get_result(self) -> int:
return await self.result
The Future
object is created in receive()
.
I have checked the id of the event loop and I found all the created tasks are in the same loop.
Hence, I wonder what can be the cause of this issue?
Thanks!
本文标签: pythonThe setresult() of Future doesn39t end the await after the loop of createtask()Stack Overflow
版权声明:本文标题:python - The set_result() of Future doesn't end the await after the loop of create_task() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741419651a2377726.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论