import time
import asyncio
from concurrent.futures import ThreadPoolExecutor
def long_blocking_function():
print(time.time())
time.sleep(2)
return True
async def run():
loop = asyncio.get_event_loop()
# 新建線程池
pool = ThreadPoolExecutor()
# 任務列表
tasks = [loop.run_in_executor(pool, long_blocking_function),
loop.run_in_executor(pool, long_blocking_function)]
# 等待所有任務結束並返回
return await asyncio.gather(*tasks)
if __name__ == '__main__':
# 獲取新的事件循環
loop = asyncio.new_event_loop()
# 設置當前事件循環
asyncio.set_event_loop(loop)
now = time.time()
loop.run_until_complete(run())
print(time.time() - now)