无异步操作代码
利用time.sleep使得线程挂起,模拟阻塞运行。
async def hello(x):
print(x,'Hello World:%s' % time.time())
time.sleep(1)
print(x,'Hello World:%s' % time.time())
def run():
print(time.time())
tasks = [asyncio.ensure_future(hello(1)),
asyncio.ensure_future(hello(2)),
asyncio.ensure_future(hello(3)),
asyncio.ensure_future(hello(4)),
asyncio.ensure_future(hello(5)),]
loop.run_until_complete(asyncio.wait(tasks))
if __name__ =='__main__':
loop = asyncio.get_event_loop()
run()
print('123')
异步操作代码
用asyncio.sleep模拟异步阻塞运行。
async def hello(x):
print(x,'Hello World:%s' % time.time())
await asyncio.sleep(1)
print(x,'Hello World:%s' % time.time())
def run():
print(time.time())
tasks = [asyncio.ensure_future(hello(1)),
asyncio.ensure_future(hello(2)),
asyncio.ensure_future(hello(3)),
asyncio.ensure_future(hello(4)),
asyncio.ensure_future(hello(5)),]
loop.run_until_complete(asyncio.wait(tasks))
if __name__ =='__main__':
loop = asyncio.get_event_loop()
run()
print('123')
执行结果
无异步
异步
结论
异步操作可以在程序执行到阻塞任务时,释放权限执行下一个任务,这样就可以缩短程序运行的时间。