python 异步io asyncio run_in_executor 超时处理

实例:

future = loop.run_in_executor(None, long_running_function)
result = await asyncio.wait_for(future, timeout, loop=loop)

当达到超时时,将抛出 `asyncio.futures.TimeoutError`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`tornado.concurrent.run_on_executor` 是 Tornado 提供的一个装饰器,用于在异步函数中将 CPU 密集型操作转移到线程池中执行,从而避免阻塞 I/O 循环。 具体来说,`run_on_executor` 将一个异步函数转化为一个协程,该协程通过 `concurrent.futures.ThreadPoolExecutor` 的线程池来执行函数中的 CPU 密集型操作。`ThreadPoolExecutor` 是 Python 标准库中的一个线程池实现,可以在 `tornado.concurrent` 模块中以 `Future` 的形式使用。 使用 `run_on_executor` 装饰器可以实现将 CPU 密集型操作从 I/O 循环中分离出来,提高了应用程序的并发性能和响应速度。但是,由于线程池中的线程是有限的,如果使用不当,可能会导致线程池中的线程耗尽,从而影响应用程序的性能。 示例代码: ```python from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor() @run_on_executor(executor) async def cpu_bound_task(): # CPU-bound task return async def some_handler(): # I/O-bound task await some_async_io_operation() # CPU-bound task await cpu_bound_task() # I/O-bound task await some_other_async_io_operation() ``` 在上面的代码中,`cpu_bound_task` 函数被装饰为一个协程,并通过 `ThreadPoolExecutor` 在一个线程池中执行。在 `some_handler` 函数中,`cpu_bound_task` 函数被调用,由于它被装饰成了协程,因此不会阻塞 I/O 循环。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值