python 使用@run_on_executor 创建线程,写异步请求

本文介绍了一种使用Python的concurrent.futures和tornado库实现接口异步处理的方法,通过ThreadPoolExecutor和run_on_executor装饰器,可以轻松将阻塞操作转换为异步执行,提高Web服务的响应速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor

# 只需要引入这两个包,加上@run_on_executor注解即可  凡是请求当前get的接口都是异步

@run_on_executor
def get(self, url=None):

 

`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、付费专栏及课程。

余额充值