python asyncio协程使用说明

无异步操作代码

利用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')

执行结果

无异步

在这里插入图片描述

异步

在这里插入图片描述

结论

异步操作可以在程序执行到阻塞任务时,释放权限执行下一个任务,这样就可以缩短程序运行的时间。


版权声明:本文为youngdianfeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。