用法:
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。