64 - 你了解协程吗?
【摘要】 协程的概念
协程: 又称为微线程、纤程,英文名: Coroutine通过 async/await 语法进行声明,是编写异步应用的推荐方式
import asyncio
async def main(): print('hello') await asyncio.sleep(1) print('world') # python
# asyncio.run(main...
协程的概念
- 协程: 又称为微线程、纤程,英文名: Coroutine
- 通过 async/await 语法进行声明,是编写异步应用的推荐方式
import asyncio
async def main(): print('hello') await asyncio.sleep(1) print('world') # python
# asyncio.run(main())
# jupyter
await main()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
hello
world
- 1
- 2
协程中有哪两个运行任务的函数,如何使用
import asyncio
import time
async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def myfun(): print(f'开始时间: {time.strftime("%X")}') await say_after(1, 'hello') await say_after(2, 'world') print(f'执行完成: {time.strftime("%X")}') # python
# asyncio.run(main())
# jupyter
await myfun()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
开始时间: 21:32:12
hello
world
执行完成: 21:32:15
- 1
- 2
- 3
- 4
'''
create_task
'''
async def myfun1(): task1 = asyncio.create_task( say_after(1, 'hello') ) task2 = asyncio.create_task( say_after(2, 'world') ) print(f'开始时间: {time.strftime("%X")}') await task1 await task2 print(f'结束时间: {time.strftime("%X")}') await myfun1()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
开始时间: 21:36:08
hello
world
结束时间: 21:36:10
- 1
- 2
- 3
- 4
文章来源: ruochen.blog.csdn.net,作者:若尘,版权归原作者所有,如需转载,请联系作者。
原文链接:ruochen.blog.csdn.net/article/details/104851636
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)