python - How does the asyncio module work, why is my updated sample running synchronously? -


i have tried following code in python 3.6 asyncio: example 1:

import asyncio import time  async def hello():      print('hello')     await asyncio.sleep(1)     print('hello again')  tasks=[hello(),hello()]     loop=asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) 

output expected:

hello hello hello again hello again 

then want change asyncio.sleep def:

async def sleep():     time.sleep(1)  async def hello():      print('hello')     await sleep()     print('hello again')   tasks=[hello(),hello()]     loop=asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) 

output:

hello hello again hello hello again 

it seems not running in asynchronous mode, normal sync mode.

the question is: why not running in asynchronous mode , how can change old sync module 'async' one?

asyncio uses event loop, selects coroutine in queue activate next. event loop can make intelligent decisions coroutine ready actual work. why event loop responsible creating connections , watching file descriptors , other i/o primitives; gives event loop insight when there i/o operations in progress or when results available process.

whenever use await, coroutine added event loop queue. coroutine picked execution depends on exact implementation; asyncio reference implementation offers multiple choices, there other implementations, such very, efficient uvloop implementation.

your sample still asynchronous. happens replacing await.sleep() synchronous time.sleep() call, inside new coroutine function, introduced 2 coroutines queue don't yield, , influenced in order executed. executed in appears synchronous order coincidence. if switched event loops, or introduced more coroutines (especially use i/o), order can different again.

moreover, new coroutines use time.sleep(); makes coroutines uncooperative. event loop not notified code waiting (time.sleep() not yield!), no other coroutine can executed while time.sleep() running. time.sleep() doesn't return or lets other code run until requested amount of time has passed. contrast asyncio.sleep() implementation, yields event loop call_later() hook; event loop knows that coroutine won't need attention until later time.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -