从Python3.2开始,标准库为我们提供了concurrent.futures 模块,它提供了 ThreadPoolExecutor (线程池)和 ProcessPoolExecutor (进程池)两个类。

相比 threading 等模块,该模块通过 submit 返回的是一个 future 对象,它是一个未来可期的对象,通过它可以获取某一个线程执行的状态或者某一个任务执行的状态及返回值:

  1. 主线程可以获取某一个线程(或者任务的)的状态,以及返回值。
  2. 当一个线程完成的时候,主线程能够立即知道。

基础语法介绍

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[4,5,2,3] # 创建一个最大容纳数量为2的线程池
pool= ThreadPoolExecutor(max_workers=2) # 通过submit提交执行的函数到线程池中
all_task=[pool.submit(action, i) for i in lists] # 通过result来获取返回值
result=[i.result() for i in all_task]
print(f"result:{result}") print("----complete-----")
# 线程池关闭
pool.shutdown()

返回结果:

4
5
2
3
result:[4, 5, 2, 3]
----complete-----

使用上下文管理器

可以通过 with 关键字来管理线程池,当线程池任务完成之后自动关闭线程池。

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[4,5,2,3]
all_task = []
with ThreadPoolExecutor(max_workers=2) as pool:
for second in lists:
all_task.append(pool.submit(action, second)) result=[i.result() for i in all_task]
print(f"result:{result}")
4
5
2
3
result:[4, 5, 2, 3]

等待所有子线程完成

在需要返回值的场景下,主线程需要等到所有子线程返回再进行下一步,阻塞在当前。比如下载图片统一保存,这时就需要在主线程中一直等待,使用wait方法完成。

wait(fs, timeout=None, return_when=ALL_COMPLETED)

wait 接受三个参数:

fs: 表示需要执行的序列

timeout: 等待的最大时间,如果超过这个时间即使线程未执行完成也将返回

return_when:表示wait返回结果的条件,默认为 ALL_COMPLETED 全部执行完成再返回,可选 FIRST_COMPLETED

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed lists=[4,5,2,3]
all_task = []
with ThreadPoolExecutor(max_workers=2) as pool:
for second in lists:
all_task.append(pool.submit(action, second)) # 主线程等待所有子线程完成
wait(all_task, return_when=ALL_COMPLETED)
print("----complete-----")
4
5
2
3
----complete-----

等待第一个子线程完成

wait 方法可以设置等待第一个子线程返回就继续执行,表现为主线程在第一个线程返回后便不会阻塞,继续执行下面的操作。

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[4,5,2,3]
all_task = []
with ThreadPoolExecutor(max_workers=2) as pool:
for second in lists:
all_task.append(pool.submit(action, second)) # 主线程等待第一个子线程完成
wait(all_task, return_when=FIRST_COMPLETED)
print("----complete-----")
4
5
2
----complete-----
3

因为result方法是阻塞的,所以流程会在result这里阻塞直到所有子线程返回,相当于 ALL_COMPLETED 方法。

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[4,5,2,3]
all_task = []
with ThreadPoolExecutor(max_workers=2) as pool:
for second in lists:
all_task.append(pool.submit(action, second)) # 主线程等待第一个子线程完成
wait(all_task, return_when=FIRST_COMPLETED)
print("----first complete-----") result=[i.result() for i in all_task]
print(f"result:{result}")
print("----complete-----")
4
5
2
----first complete-----
3
result:[4, 5, 2, 3]
----complete-----

返回及时处理

如果不需要等待所有线程全部返回,而是每返回一个子线程就立刻处理,那么就可以使用as_completed获取每一个线程的返回结果。

as_completed() 方法是一个生成器,在没有任务完成的时候,会一直阻塞。当有某个任务完成的时候,会 yield 这个任务,就能执行 for 循环下面的语句,然后继续阻塞住,循环到所有的任务结束。同时,先完成的任务会先返回给主线程。

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[4,5,2,3]
all_task = []
with ThreadPoolExecutor(max_workers=2) as pool:
for second in lists:
all_task.append(pool.submit(action, second)) for future in as_completed(all_task):
print(f"{future.result()} 返回") print("----complete-----")
4
5
2
4 返回
3
5 返回
2 返回
3 返回
----complete-----

map

map 方法是对序列中每一个元素都执行 action 方法,主要有两个特点:

  1. 不需要将任务submit到线程池
  2. 返回结果的顺序和元素的顺序相同,即使子线程先返回也不会获取结果
map(fn, *iterables, timeout=None)

fn: 第一个参数 fn 是需要线程执行的函数;

iterables:第二个参数接受一个可迭代对象;

timeout: 第三个参数 timeout 跟 wait() 的 timeout 一样,但由于 map 是返回线程执行的结果,如果 timeout小于线程执行时间会抛异常 TimeoutError。

import time
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED, as_completed def action(second):
print(second)
time.sleep(second)
return second lists=[5,1,2,3]
with ThreadPoolExecutor(max_workers=2) as pool:
for result in pool.map(action, lists):
print(f"{result} 返回")
5
1
2
3
5 返回
1 返回
2 返回
3 返回

可以看出返回结果和列表的结果一致,即使第2个元素只需要1s就能返回,也还是等待第一个5s线程返回只有才有结果。

python 线程池 ThreadPoolExecutor的更多相关文章

  1. python线程池ThreadPoolExecutor(上)(38)

    在前面的文章中我们已经介绍了很多关于python线程相关的知识点,比如 线程互斥锁Lock / 线程事件Event / 线程条件变量Condition 等等,而今天给大家讲解的是 线程池ThreadP ...

  2. python线程池ThreadPoolExecutor与进程池ProcessPoolExecutor

    python中ThreadPoolExecutor(线程池)与ProcessPoolExecutor(进程池)都是concurrent.futures模块下的,主线程(或进程)中可以获取某一个线程(进 ...

  3. python线程池ThreadPoolExecutor用法

    线程池concurrent.futures.ThreadPoolExecutor模板 import time from concurrent.futures import ThreadPoolExec ...

  4. python线程池 ThreadPoolExecutor 的用法及实战

    写在前面的话 (https://jq.qq.com/?_wv=1027&k=rX9CWKg4) 文章来源于互联网从Python3.2开始,标准库为我们提供了 concurrent.future ...

  5. Python线程池ThreadPoolExecutor源码分析

    在学习concurrent库时遇到了一些问题,后来搞清楚了,这里记录一下 先看个例子: import time from concurrent.futures import ThreadPoolExe ...

  6. Python 线程池(小节)

    Python 线程池(小节) from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import os,time, ...

  7. python线程池示例

    使用with方式创建线程池,任务执行完毕之后,会自动关闭资源 , 否则就需要手动关闭线程池资源  import threading, time from concurrent.futures impo ...

  8. Python线程池与进程池

    Python线程池与进程池 前言 前面我们已经将线程并发编程与进程并行编程全部摸了个透,其实我第一次学习他们的时候感觉非常困难甚至是吃力.因为概念实在是太多了,各种锁,数据共享同步,各种方法等等让人十 ...

  9. java线程池ThreadPoolExecutor使用简介

    一.简介线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为:ThreadPoolExecutor(int corePoolSize, int m ...

  10. 线程池ThreadPoolExecutor

    线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为: ThreadPoolExecutor(int corePoolSize, int maxi ...

随机推荐

  1. Linux Media 子系统链路分析

    一.概述 Media 子系统是一个用于处理多媒体设备的框架,它提供了一组 API 和驱动程序,用于管理和控制视频.音频和其他多媒体设备.而 V4L2 是 media 子系统的一部分,用于处理视频相关的 ...

  2. 数论笔记(Full Version)

    数论笔记(Full Version) 一.数论基础: 1.整除: 重新定义除法: 对于计算式:\(a\div b\) 来说,其结果可以变化为以下的式子:$$a = b\lfloor \frac{a}{ ...

  3. 改变element dialog弹窗的关闭按钮样式

    .el-dialog__headerbtn { top: 8px !important; background: url('https://你路径资源的url图片') left no-repeat; ...

  4. webpack配置局域网访问项目

    要配置webpack允许局域网访问项目,你需要做以下几个步骤:   1. 在webpack配置文件中,找到devServer选项,并设置其属性`host`为`0.0.0.0`.这将允许其他设备通过局域 ...

  5. Codeforces Round #703 (Div. 2) A、B、D、E题解

    写在前边 链接:Codeforces Round #703 (Div. 2) 这次的交互题是真不会做. A. Shifting Stacks 链接:A题链接 题目大意: 有\(n\)摞高度分别为\(h ...

  6. 国内 AI 成图第一案!你来你会怎么判?

    我国目前并未出台专门针对网络爬虫技术的法律规范,但在司法实践中,相关判决已屡见不鲜,K 哥特设了"K哥爬虫普法"专栏,本栏目通过对真实案例的分析,旨在提高广大爬虫工程师的法律意识, ...

  7. 关于git 解决分支冲突问题(具体操作,包含截图,教你一步一步解决冲突问题)

    当在Git中有多个开发者在同一个分支上工作时,可能会发生分支冲突.分支冲突指的是多个开发者在同一时间修改相同的代码文件,导致Git无法自动合并这些更改. 比如说:我在github上进行了md文件的修改 ...

  8. [USACO2022OPEN S] COW Operations S

    题目描述 Bessie 找到了一个长度不超过 \(2 \cdot 10^5\) 且仅包含字符 'C','O' 和 'W' 的字符串 \(s\).她想知道是否可以使用以下操作将该字符串变为单个字母 'C ...

  9. Spring+SpringMVC+Mybatis+Vue+Axios+Thymeleaf整合案例

    1.创建SSM-Parent父项目 修改配置文件 <?xml version="1.0" encoding="UTF-8"?> <projec ...

  10. LeetCode331:验证二叉树的前序序列化(递归)

    解题思路:把所有元素存成数组,设置一个全局下标next,表示当前节点如果要继续遍历应当从数组的哪个位置开始,然后从下标 0 开始DFS.如果DFS返回真并且next下标等于数组的长度,说明元素已经全部 ...