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.