用法:
awaitable loop.run_in_executor(executor, func, *args)
安排在指定的執行程序中調用
func
。executor
參數應該是一個concurrent.futures.Executor
實例。如果executor
是None
,則使用默認執行程序。例子:
import asyncio import concurrent.futures def blocking_io(): # File operations (such as logging) can block the # event loop: run them in a thread pool. with open('/dev/urandom', 'rb') as f: return f.read(100) def cpu_bound(): # CPU-bound operations will block the event loop: # in general it is preferable to run them in a # process pool. return sum(i * i for i in range(10 ** 7)) async def main(): loop = asyncio.get_running_loop() ## Options: # 1. Run in the default loop's executor: result = await loop.run_in_executor( None, blocking_io) 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, blocking_io) print('custom thread pool', result) # 3. Run in a custom process pool: with concurrent.futures.ProcessPoolExecutor() as pool: result = await loop.run_in_executor( pool, cpu_bound) print('custom process pool', result) asyncio.run(main())
此方法返回一個
asyncio.Future
對象。使用
functools.partial()
將關鍵字參數傳遞給func
。在 3.5.3 版中更改:asyncio.loop.run_in_executor不再配置
max_workers
它創建的線程池執行器,而不是將其留給線程池執行器(ThreadPoolExecutor
) 設置默認值。
相關用法
- Python asyncio.loop.shutdown_asyncgens用法及代碼示例
- Python asyncio.BaseTransport.get_extra_info用法及代碼示例
- Python asyncio.shield用法及代碼示例
- Python asyncio.run用法及代碼示例
- Python asyncio.wait_for用法及代碼示例
- Python asyncio.create_task用法及代碼示例
- Python asyncio.Task.cancel用法及代碼示例
- Python asyncio.Server用法及代碼示例
- Python asyncio.Server.serve_forever用法及代碼示例
- Python asyncio.Event用法及代碼示例
- Python asyncio.gather用法及代碼示例
- Python asyncio.sleep用法及代碼示例
- Python asyncio.to_thread用法及代碼示例
- Python asyncio.Condition用法及代碼示例
- Python asyncio.SelectorEventLoop用法及代碼示例
- Python asyncio.run_coroutine_threadsafe用法及代碼示例
- Python asyncio.Lock用法及代碼示例
- Python asyncio.Future.add_done_callback用法及代碼示例
- Python asyncio.as_completed用法及代碼示例
- Python asyncio.Semaphore用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 asyncio.loop.run_in_executor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。