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 - 請解釋什麼是線程鎖,以及如何使用線程鎖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章