python 异步api ThreadPoolExecutor 、ProcessPoolExecutor(多线程、多进程)

python 异步api ThreadPoolExecutor 、ProcessPoolExecutor(多线程、多进程)
  • python==3.7
线程
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures._base import Future
from random import randint

worker_num = 5
executor = ThreadPoolExecutor(worker_num )


def do_something(num):

    res = f"*{num}{'='* randint(1, 6)}"
    print(res)
    time.sleep(5)
    return res


def test_thread():
    # 存放执行状态
    wait_for = []
    for x in range(0, 10):
        future = executor.submit(do_something, x)
        future.done()
        wait_for.append(future)

    # # ALL_COMPLETED等线程中任务全部执行完成再往下执行
    # wait(wait_for, timeout=10, return_when=ALL_COMPLETED)

    # as_completed方法是一个生成器,在没有任务完成的时候,会一直阻塞,除非设置了 timeout
    # 当有某个任务完成的时候,会 yield 这个任务,就能执行 for 循环下面的语句,然后继续阻塞住,循环到所有的任务结束
    f: Future
    for f in as_completed(wait_for, timeout=10):

        # 被调方法的return值
        result = f.result()
        # 该任务是否完成
        is_done = f.done()

    print("====end====")


if __name__ == '__main__':
    test_thread()
进程

进程使用跟上面类似

from concurrent.futures import ProcessPoolExecutor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要对异步函数进行多线程并发,可以使用Python的`concurrent.futures`模块来实现。`concurrent.futures`提供了一个高级接口,用于以异步方式执行可调用对象。 首先,确保你的异步函数是使用`async def`关键字定义的协程函数。然后,可以使用`concurrent.futures.ThreadPoolExecutor`来创建一个线程池,通过提交任务给线程池来执行协程函数。 下面是一个示例代码,演示了如何对异步函数进行多线程并发: ```python import asyncio import concurrent.futures async def async_task(n): print(f'Starting task {n}') await asyncio.sleep(1) print(f'Ending task {n}') return n async def main(): with concurrent.futures.ThreadPoolExecutor() as executor: loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(executor, async_task, i) for i in range(5)] results = await asyncio.gather(*tasks) print(results) asyncio.run(main()) ``` 在上面的示例中,`async_task`是一个异步函数,它会打印任务编号,并在执行后等待1秒钟。`main`函数使用`concurrent.futures.ThreadPoolExecutor`创建了一个线程池,并使用`asyncio.run_in_executor`将异步函数提交给线程池执行。最后,使用`asyncio.gather`等待所有任务完成,并打印结果。 注意,这里使用的是线程池而不是进程池,因为异步函数在事件循环中执行,而不是在主线程中执行。如果要在多个进程中执行异步函数,可以使用`concurrent.futures.ProcessPoolExecutor`代替`ThreadPoolExecutor`。 希望这个示例能帮助你理解如何对异步函数进行多线程并发。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuhengshi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值