一、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 对象,它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值:

  1. 主线程可以获取某一个线程(或者任务的)的状态,以及返回值。
  2. 当一个线程完成的时候,主线程能够立即知道。
  3. 让多线程和多进程的编码接口一致。

线程池的基本使用

#!/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)
wait 接受三个参数:

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

上面虽提供了判断任务是否结束的方法,但是不能在主线程中一直判断。最好的方法是当某个任务结束了,就给主线程返回结果,而不是一直判断每个任务是否结束。

concurrent.futures 中 的 as_completed() 就是这样一个方法,当子线程中的任务执行完后,直接用 result() 获取返回结果
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的更多相关文章

  1. python线程池(threadpool)

    一.安装 pip install threadpool 二.使用介绍 (1)引入threadpool模块 (2)定义线程函数 (3)创建线程 池threadpool.ThreadPool() (4)创 ...

  2. python线程池(threadpool)模块使用笔记

    一.安装与简介 pip install threadpool pool = ThreadPool(poolsize) requests = makeRequests(some_callable, li ...

  3. python线程池(threadpool)模块使用笔记 .python 线程池使用推荐

    一.安装与简介 pip install threadpool pool = ThreadPool(poolsize) requests = makeRequests(some_callable, li ...

  4. Python 线程池(小节)

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

  5. Python之路(第四十六篇)多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)

    一.线程池 很久(python2.6)之前python没有官方的线程池模块,只有第三方的threadpool模块, 之后再python2.6加入了multiprocessing.dummy 作为可以使 ...

  6. python3 线程池-threadpool模块与concurrent.futures模块

    多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...

  7. Python3【模块】concurrent.futures模块,线程池进程池

    Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要 ...

  8. python并发模块之concurrent.futures(一)

    Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threadin ...

  9. Python之网络编程之concurrent.futures模块

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

随机推荐

  1. MySQL数据库之大厂面试必备技能v8.0.27

    概述 **本人博客网站 **IT小神 www.itxiaoshen.com 定义 MySQL官方地址 https://www.mysql.com/ MySQL 8系列最新版本为8.0.27,5系列的最 ...

  2. 决策单调性&wqs二分

    其实是一个还算 trivial 的知识点吧--早在 2019 年我就接触过了,然鹅当时由于没认真学并没有把自己学懂,故今复学之( 1. 决策单调性 引入:在求解 DP 问题的过程中我们常常遇到这样的问 ...

  3. 对 SAM 和 PAM 的一点理解

    感觉自己学 SAM 的时候总有一种似懂非懂.云里雾里.囫囵吞枣.不求甚解的感觉,是时候来加深一下对确定性有限状态自动机的理解了. 从 SAM 的定义上理解:SAM 可以看作一种加强版的 Trie,它可 ...

  4. DirectX12 3D 游戏开发与实战第八章内容(下)

    DirectX12 3D 游戏开发与实战第八章内容(下) 8.9.材质的实现 下面是材质结构体的部分代码: // 简单的结构体来表示我们所演示的材料 struct Material { // 材质唯一 ...

  5. nginx_access_log的格式设置

    log_format <NAME> <Strin­­­g>; 关键字 格式标签 日志格式 关键字:其中关键字error_log不能改变 格式标签:格式标签是给一套日志格式设置一 ...

  6. cd-hit 去除冗余序列

    最近一篇NG中使用到的软件,用来去除冗余的contigs,现简单记录. CD-HIT早先是一个蛋白聚类的软件,其主要的特定就是快!(ps:不是所有快的都是好的) 其去除冗余序列的大概思路就是: 首先对 ...

  7. 38- Majority Element

    Majority Element My Submissions QuestionEditorial Solution Total Accepted: 110538 Total Submissions: ...

  8. 重学Git(一)

    一.最最最基础操作 # 初始化仓库 git init # 添加文件到暂存区 git add readme.md # 提交 git commit -m 'wrote a readme file' 二.简 ...

  9. JavaIO——System对IO的支持、序列化

    1.系统类对IO的支持 在我们学习PriteWriter.PrintStream里面的方法print.println的时候是否观察到其与我们之前一直使用的系统输出很相似呢?其实我们使用的系统输出就是采 ...

  10. javaAPI1

    Iterable<T>接口, Iterator<T> iterator() Collection<E>:接口,add(E e) ,size() , Object[] ...