1

Recently,I learned how to code Asynchronous programming in Python.And I see the following example.

async def a():
    print('starta')
    asyncio.sleep(3)
    print('enda')

async def b():
    print('startb')
    asyncio.sleep(3)
    print('endb')

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([a(),b()]))

then we can see output:

starta
startb
(wait for about 3 seconds)
enda
endb

why use asyncio.sleep() here, what is the different between asyncio.sleep() and time.sleep()? I heared that asyncio.sleep() is used for Asynchronous IO simulation.so I try following code:

async def _():
    #Visit a very time-consuming website
    requests.get(url).content

async def a():
    print('starta')
    await _()
    print('enda')

async def b():
    print('startb')
    await _()
    print('endb')

start = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([a(),b()]))

I replace asyncio.sleep with an time-consuming operation(visit a website) however, the output is:

starta
enda
(wait for about 3 seconds)
startb
endb

Can anyone tell me why?Thanks a lot.

JieamI
  • 140
  • 5
  • 2
    ``requests.get`` is blocking, just like ``time.sleep``. Hiding it in an ``async def`` function does not change that. – MisterMiyagi Jun 02 '20 at 10:33
  • 2
    It should properly be `await asyncio.sleep(3)`…!? – deceze Jun 02 '20 at 10:34
  • Does this answer your question? [Difference between `asyncio.wait([asyncio.sleep(5)])` and `asyncio.sleep(5)`](https://stackoverflow.com/questions/62001898/difference-between-asyncio-waitasyncio-sleep5-and-asyncio-sleep5) – MisterMiyagi Jun 02 '20 at 10:36
  • In a nutshell: with `asyncio`, only one thing can run at any one time, it's *cooperative multitasking*. The "cooperative" part is that whenever any `async` function uses `await`, it allows some other task to run. `await` yields control back to the event loop, which will schedule another task to run. Without `await`, one task will continue to run until its end and block everything else from running. – deceze Jun 02 '20 at 10:39
  • Thanks a lot.however,for blocking operations like `requests.get`, is there anyway to make it non-blocking?I have tried aiohttp, It can achieve the effect I want perfectly.How does it work? – JieamI Jun 02 '20 at 13:01
  • The function that you're making a call to and that you're `await`ing needs to be specifically `async`. `requests.get` isn't `async`, it doesn't play in the `asyncio` model. You can execute any old non-async function in an async way using [`run_in_executor`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor), which shunts it off into a separate thread (take care that the function is thread-safe). aiohttp is an HTTP library made for `asyncio`. – deceze Jun 02 '20 at 13:10
  • I appreciate it. – JieamI Jun 02 '20 at 14:09

0 Answers0