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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yuhengshi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值