0

In the asynchronous code below, what is the thing that checks if the response is ready, for each task to resume the execution ?

I understand that the 50 requests are all sent one after another at async with session.get(url).

But how does it then checks that responses are ready ?

Is it the event loop, that periodically checks ?

Is it asyncio that "yields" control from one task to another to see if a response is ready ?

import aiohttp
import asyncio
import time

async def fetch_page(url):
    page_start = time.time()
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            print(f'Page took {time.time() - page_start}')
            return response.status

loop = asyncio.get_event_loop()
tasks = [fetch_page('http://google.com') for i in range(50)]
start = time.time()
loop.run_until_complete(asyncio.gather(*tasks))
print(f'All took {time.time() - start}')
trogne
  • 3,402
  • 3
  • 33
  • 50
  • `async with session.get(url)` – Klaus D. Sep 29 '20 at 02:13
  • Yes, but behind the scenes, how does it do to prevent waiting times of longer requests ? – trogne Sep 29 '20 at 02:15
  • Inside `async with session.get(url)`, does asyncio do something like suspending the task after sending the request, yielding control to the other task/request ? – trogne Sep 29 '20 at 02:21
  • Of cause, it wouldn't be async if it wouldn't do that. You are free to check the [source code](https://github.com/aio-libs/aiohttp/blob/90acab1c42eed1984bdd4201bd082c5983213ffc/aiohttp/client.py#L468) for details. We warned: it's complex and you might have to dive a couple of levels deeper. – Klaus D. Sep 29 '20 at 02:36

0 Answers0