Z
Z
zlodiak2019-11-10 19:53:33
Python
zlodiak, 2019-11-10 19:53:33

How does asyncio parallelize tasks?

Let's say that 3 http requests are made using the asyncio module.

import asyncio
import aiohttp

urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']

async def call_url(url):
    print('Starting {}'.format(url))
    response = await aiohttp.get(url)
    data = await response.text()
    print('{}: {} bytes: {}'.format(url, len(data), data))
    return data

futures = [call_url(url) for url in urls]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(futures))

Please tell me if I understand what is happening correctly:
  • 1. The asyncio module's event loop accepts three functions
  • 2. puts each of them in a separate thread
  • 3. each of them is converted into a coroutine in a separate thread
  • 4. which returns the result after receiving the data via http
  • 5. but until this data is received, the GIL switches these threads every 0.005 sec
  • 6. in this way, the received data will be displayed in the order of completion of http requests (the sooner an http request is successfully processed in any coroutine, the sooner its results will be displayed on the screen)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-11-10
@zlodiak

puts each of them in a separate thread

No, there is only one thread. That's the whole point of asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question