2
votes

I'm trying to implement fair queuing in my library that is based on asyncio.

In some function, I have a statement like (assume socketX are tasks):

done, pending = asyncio.wait(
    [socket1, socket2, socket3],
    return_when=asyncio.FIRST_COMPLETED,
)

Now I read the documentation for asyncio.wait many times but it does not contain the information I'm after. Mainly, I'd like to know if:

  • socket1, socket2 and socket3 happened to be already ready when I issue the call. Is it guaranteed that done will contain them all or could it be that it returns only one (or two) ?
  • In the second case, does the order of the tasks passed to wait() matter ?

I'm trying to assert if I can just apply fair-queuing in the set of done tasks (by picking one and leaving the other tasks for later resolution) or if I also need to care about the order I pass the tasks in.

The documentation is kinda silent about this. Any idea ?

1

1 Answers

4
votes

This is only taken according to the source code of Python 3.5.

If the future is done before calling wait, they will all be placed in the done set:

import asyncio

async def f(n):
    return n

async def main():
    (done, pending) = await asyncio.wait([f(1), f(2), f(3)], return_when=asyncio.FIRST_COMPLETED)
    print(done)     # prints set of 3 futures
    print(pending)  # prints empty set

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()