64 - 你了解协程吗?

协程的概念

  • 协程: 又称为微线程、纤程,英文名: Coroutine
  • 通过 async/await 语法进行声明,是编写异步应用的推荐方式
import asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

    

# python 
# asyncio.run(main())
# jupyter
await main()
hello
world

协程中有哪两个运行任务的函数,如何使用

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()
开始时间: 21:32:12
hello
world
执行完成: 21:32:15
'''
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()
开始时间: 21:36:08
hello
world
结束时间: 21:36:10

65 - 请解释什么是线程锁,以及如何使用线程锁

发布了208 篇原创文章 · 获赞 249 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_29339467/article/details/104851636
64