Python 线程池模块threadpool 、 concurrent.futures 的 ThreadPoolExecutor
一、threadpool 基本用法
pip install threadpool
pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()
第一行定义了一个线程池,表示最多可以创建poolsize这么多线程;
第二行是调用makeRequests创建了要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数可以不写,default是无,也就是说makeRequests只需要2个参数就可以运行;
第三行使用列表生成式代替for循环,是将所有要运行多线程的请求扔进线程池,
[pool.putRequest(req) for req in requests]等同于
for req in requests:
pool.putRequest(req)
第四行是等待所有的线程完成工作后退出。
二、代码实例
要处理的函数,只需要一个传参:
import time
import threadpool
def sayhello(str):
print "Hello ",str
time.sleep(2) name_list =['xiaozi','aa','bb','cc']
start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print '%d second'% (time.time()-start_time)
要处理的函数,只需要N个传参:
方式一:---参数列表元素需要用元组,([args,...], None)
import time
import threadpool
def sayhello(a, b, c):
print("Hello ",a, b, c)
time.sleep(2) def call_back():
print('call_back...........') name_list = [([1,2,3], None), ([4,5,6], None) ] start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print('%d second'% (time.time()-start_time))
Hello 1 2 3
Hello 4 5 6
2 second
Process finished with exit code 0
方式二:---参数列表元素需要用元组,(None, {'key':'value', .......})
import time
import threadpool
def sayhello(a, b, c):
print("Hello ",a, b, c)
time.sleep(2) def call_back():
print('call_back...........') # name_list = [([1,2,3], None), ([4,5,6], None) ]
name_list = [(None, {'a':1,'b':2,'c':3}), (None, {'a':4,'b':5, 'c':6}) ] start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print('%d second'% (time.time()-start_time))
concurrent.futures 的ThreadPoolExecutor (线程池)
https://www.jianshu.com/p/6d6e4f745c27
从Python3.2开始,标准库为我们提供了 concurrent.futures 模块,它提供了 ThreadPoolExecutor (线程池)和ProcessPoolExecutor (进程池)两个类。
相比 threading 等模块,该模块通过 submit 返回的是一个 future 对象,它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值:
- 主线程可以获取某一个线程(或者任务的)的状态,以及返回值。
- 当一个线程完成的时候,主线程能够立即知道。
- 让多线程和多进程的编码接口一致。
线程池的基本使用
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/11/21 17:55
# @Author:zhangmingda
# @File: ThreadPoolExecutor_study.py
# @Software: PyCharm
# Description: from concurrent.futures import ThreadPoolExecutor
import time task_args_list = [('zhangsan', 2),('lishi',3), ('wangwu', 4)]
def task(name, seconds):
print('% sleep %s seconds start...' % (name, seconds))
time.sleep(seconds)
print('% sleep %s seconds done' % (name, seconds))
return '%s task done' % name with ThreadPoolExecutor(max_workers=5) as t:
# [ t.submit(task, *arg) for arg in task_args_list]
task1 = t.submit(task, '张三', 1)
task2 = t.submit(task, '李四', 2)
task3 = t.submit(task, '王五', 2)
task4 = t.submit(task, '赵柳', 3)
print(task1.done())
print(task2.done())
print(task3.done())
print(task4.done())
time.sleep(2)
print(task1.done())
print(task2.done())
print(task3.done())
print(task4.done()) print(task1.result())
print(task2.result())
print(task3.result())
print(task4.result())

使用 with 语句 ,通过 ThreadPoolExecutor 构造实例,同时传入 max_workers 参数来设置线程池中最多能同时运行的线程数目。
使用 submit 函数来提交线程需要执行的任务到线程池中,并返回该任务的句柄(类似于文件、画图),注意 submit() 不是阻塞的,而是立即返回。
通过使用 done() 方法判断该任务是否结束。上面的例子可以看出,提交任务后立即判断任务状态,显示四个任务都未完成。在延时2.5后,task1 和 task2 执行完毕,task3 仍在执行中。
使用 result() 方法可以获取任务的返回值 【注意result 是阻塞的会阻塞主线程】
主要方法:
wait
wait(fs, timeout=None, return_when=ALL_COMPLETED)
fs: 表示需要执行的序列
timeout: 等待的最大时间,如果超过这个时间即使线程未执行完成也将返回
return_when:表示wait返回结果的条件,默认为 ALL_COMPLETED 全部执行完成再返回;可指定FIRST_COMPLETED 当第一个执行完就退出阻塞
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED, ALL_COMPLETED
import time task_args_list = [('zhangsan', 1),('lishi',2), ('wangwu', 3)]
task_list = [] def task(name, seconds):
print('% sleep %s seconds start...' % (name, seconds))
time.sleep(seconds)
print('% sleep %s seconds done' % (name, seconds))
return '%s task done' % name with ThreadPoolExecutor(max_workers=5) as t:
[task_list.append(t.submit(task, *arg)) for arg in task_args_list]
wait(task_list, return_when=FIRST_COMPLETED) # 等了一秒
print('all_task_submit_complete! and First task complete!')
print(wait(task_list,timeout=1.5)) # 又等了1.5秒,合计等了2.5秒

as_completed
上面虽提供了判断任务是否结束的方法,但是不能在主线程中一直判断。最好的方法是当某个任务结束了,就给主线程返回结果,而不是一直判断每个任务是否结束。
task_args_list = [('zhangsan', 1),('lishi',3), ('wangwu', 2)]
task_list = []
def task(name, seconds):
print('%s sleep %s seconds start...' % (name, seconds))
time.sleep(seconds)
return '%s sleep %s seconds done' % (name, seconds)
with ThreadPoolExecutor(max_workers=5) as t:
[task_list.append(t.submit(task, *arg)) for arg in task_args_list]
[print(future.result()) for future in as_completed(task_list)]
print('All Task Done!!!!!!!!!')

map
map(fn, *iterables, timeout=None)
fn: 第一个参数 fn 是需要线程执行的函数;
iterables:第二个参数接受一个可迭代对象;
timeout: 第三个参数 timeout 跟 wait() 的 timeout 一样,但由于 map 是返回线程执行的结果,如果 timeout小于线程执行时间会抛异常 TimeoutError。
用法如下:
def spider(page):
time.sleep(page)
return page start = time.time()
executor = ThreadPoolExecutor(max_workers=4) i = 1
for result in executor.map(spider, [2, 3, 1, 4]):
print("task{}:{}".format(i, result))
i += 1 # 运行结果
task1:2
task2:3
task3:1
task4:4
使用 map 方法,无需提前使用 submit 方法,map 方法与 python 高阶函数 map 的含义相同,都是将序列中的每个元素都执行同一个函数。
上面的代码对列表中的每个元素都执行 spider() 函数,并分配各线程池。
可以看到执行结果与上面的 as_completed() 方法的结果不同,输出顺序和列表的顺序相同,就算 1s 的任务先执行完成,也会先打印前面提交的任务返回的结果。
Python 线程池模块threadpool 、 concurrent.futures 的 ThreadPoolExecutor的更多相关文章
- python线程池(threadpool)
一.安装 pip install threadpool 二.使用介绍 (1)引入threadpool模块 (2)定义线程函数 (3)创建线程 池threadpool.ThreadPool() (4)创 ...
- python线程池(threadpool)模块使用笔记
一.安装与简介 pip install threadpool pool = ThreadPool(poolsize) requests = makeRequests(some_callable, li ...
- python线程池(threadpool)模块使用笔记 .python 线程池使用推荐
一.安装与简介 pip install threadpool pool = ThreadPool(poolsize) requests = makeRequests(some_callable, li ...
- Python 线程池(小节)
Python 线程池(小节) from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import os,time, ...
- Python之路(第四十六篇)多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)
一.线程池 很久(python2.6)之前python没有官方的线程池模块,只有第三方的threadpool模块, 之后再python2.6加入了multiprocessing.dummy 作为可以使 ...
- python3 线程池-threadpool模块与concurrent.futures模块
多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...
- Python3【模块】concurrent.futures模块,线程池进程池
Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要 ...
- python并发模块之concurrent.futures(一)
Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threadin ...
- Python之网络编程之concurrent.futures模块
需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...
随机推荐
- tomcat进行远程debug
Windows下 进入目录下的bin目录,编辑打开startup.bat 在前面添加: SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.com ...
- Docker namespace,cgroup,镜像构建,数据持久化及Harbor安装、高可用配置
1.Docker namespace 1.1 namespace介绍 namespace是Linux提供的用于分离进程树.网络接口.挂载点以及进程间通信等资源的方法.可以使运行在同一台机器上的不同服务 ...
- freeswitch APR库哈希表
概述 freeswitch的核心源代码是基于apr库开发的,在不同的系统上有很好的移植性. 哈希表在开发中应用的非常广泛,主要场景是对查询效率要求较高的逻辑,是典型的空间换时间的数据结构实现. 大多数 ...
- Atcoder Typical DP Contest S - マス目(状压 dp+剪枝)
洛谷题面传送门 介绍一个不太主流的.非常暴力的做法( 首先注意到 \(n\) 非常小,\(m\) 比较大,因此显然以列为阶段,对行的状态进行状压.因此我们可以非常自然地想到一个非常 trivial 的 ...
- curl实现SFTP上传下载文件
摘自:https://blog.csdn.net/swj9099/article/details/85292444 #include <stdio.h> #include <stdl ...
- 制作nc文件(Matlab)
首先看一个nc文件中包含哪些部分,例如一个标准的 FVCOM 输入文件 wind.nc: netcdf wind { dimensions: nele = 36858 ; node = 18718 ; ...
- REPuter注释叶绿体重复序列
REPuter可注释叶绿体重复序列,包括4种类型,Forward(F), Reverse (R), Complement (C), Palindromic (P). REPuter 是可在线注释, 详 ...
- [Linux]非root的R环境被conda破坏后如何恢复?
记录说明 这篇文章本来是用来记录Linux非root环境下安装PMCMRplus包折腾过程,但后来试过了各种方法安装不上这个R包后,我换上了Miniconda来安装.经前人提醒,一开始安装Minico ...
- Yii2 源码分析 入口文件执行流程
Yii2 源码分析 入口文件执行流程 1. 入口文件:web/index.php,第12行.(new yii\web\Application($config)->run()) 入口文件主要做4 ...
- 金蝶EAS——客户端打开时,提示正在更新的文件d:\eas\client\bin\lib\proxy.jar被其他应用程序占用.请关闭
解决办法: 一.通过调用任务管理器来退出,启用任务管理器需同时按下键Ctrl+Alt+Del,在应用程序中找到金蝶EAS,单击,选择结束任务即可:或者在任务管理器中选择"进程",点 ...