Issue
I am reading the python asyncio library. The gather
function confused me. Usually, we use it in the following way.
async def func(n):
await asyncio.sleep(n)
return n
result = await asyncio.gather(func(1), func(2)) # should be [1, 2]
It looks so naturally. There are two coroutines and result
will be the list of their returns. However, I am confused by the implementation of asyncio.gather
. See code. It returns a _GatheringFuture
.
outer = _GatheringFuture(children, loop=loop)
return outer
The _GetheringFuture
class is not like Task
. It does not contain logic to call Future.set_result()
or Future.set_execption()
, so when we write await asyncio.gather(...)
, who sets the result/exception?
Solution
Ah. I see where set_result
is called. It is inside def _done_callback(fut)
. So each coroutine in the input will execute this callback. The last finished one will set result of the outer future, i.e., _GatheringFuture
.
Answered By - kevin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.