1. 程式人生 > 其它 >【協程】7、asyncio.Future物件

【協程】7、asyncio.Future物件

1、concurrent.futures.Future物件

  • 使用執行緒池、程序池實現非同步操作時用到的物件。
  • 具體參考:2020-11-16 ThreadPoolExecutor 的用法及實戰
  • 以後寫程式碼可能會存在交叉使用。例如:你的某個專案都是基於協程非同步程式設計,加入mysql不支援協程,那麼在訪問資料庫的時候只能使用執行緒或程序做非同步程式設計
# -*- coding: utf-8 -*-
import time
import asyncio
import concurrent.futures


def func1():
    # 某個耗時操作
    time.sleep(2)
    return 'SB'

async def  main():
    loop = asyncio.get_running_loop()

    # 1、run in the default loop^s executor(預設ThreadPoolExecutor)
    # 第一步:內部會先呼叫ThreadPoolExecutor的submit方法去執行緒池中申請一個執行緒去執行func1函式,並返回一個concurrent.futures。Future物件
    # 第二步:呼叫asyncio.wrap_future將concurrent.futures,Future物件包裝為asyncio.Future物件
    # 因為concurrent.futures.Future物件不支援await語法,所以需要包裝為asyncio.Future物件,才能使用。
    fut = loop.run_in_executor(None, func1)
    result = await fut
    print('default thread pool:', result)
    
    # 2. Run in a custom thread pool:
    # with concurrent.futures.ThreadPoolExecutor() as pool:
    #     result = await loop.run_in_executor(pool, func1)
    #     print('custom thread pool', result)
    
    # 3. Run in custom process pool:
    # with concurrent.futures.ProcessPoolExecutor() as pool:
    #     result = await loop.run_in_executor(pool, func1)
    #     print('custom process pool', result)