目录
- 一.Python 线程池前言
- 二.Python 线程池 ThreadPoolExecutor 常用函数
- 1.线程池 as_completed 函数使用
- 2.线程池 map 函数使用
- 3.线程池 wait 函数使用
- 三.猜你喜欢
一.Python 线程池前言紧接着上一篇文章 Python 线程池 ThreadPoolExecutor(一) 我们继续对线程池深入一点了解,其实 Python 中关于线程池,一共有两个模块:
- 1.threadpool — 是一个比较老的模块了,现在虽然还有一些人在用,但已经不再是主流了;
- 2.concurrent.futures — 目前线程池主要使用这个模块,主流模块;
1.线程池 as_completed 函数使用虽然 done 函数提供了判断任务是否结束的方法,但是并不是太实用,因为我们并不知道线程到底什么时候结束,需要一直判断每个任务有没有结束 。这时就可以使用 as_completed 方法一次取出所有任务的结果 。
as_completed 方法是一个生成器,在没有任务完成的时候,会阻塞,在有某个任务完成的时候,就能继续执行 for 循环后面的语句,然后继续阻塞住,循环到所有的任务结束 。
# !usr/bin/env python# -*- coding:utf-8 _*-"""@Author:猿说编程@Blog(个人博客地址): www.codersrc.com@File:Python 线程池 ThreadPoolExecutor.py@Time:2021/05/05 07:37@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!"""from concurrent.futures import ThreadPoolExecutor, as_completedimport time# 参数times用来模拟网络请求的时间def download_video(index):time.sleep(2)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2)urls = [1, 2, 3, 4, 5]all_task = [executor.submit(download_video, (url)) for url in urls]for task in as_completed(all_task):data = https://tazarkount.com/read/task.result()print("任务{} down load success".format(data))'''输出结果:download video 1 finished at 2021-05-05 07:10:00任务1 down load successdownload video 2 finished at 2021-05-05 07:10:00任务2 down load successdownload video 3 finished at 2021-05-05 07:10:02任务3 down load successdownload video 4 finished at 2021-05-05 07:10:02任务4 down load successdownload video 5 finished at 2021-05-05 07:10:04任务5 down load success'''代码分析:5 个任务,2 个线程,由于在线程池构造的时候允许同时最多执行 2 个线程,所以同时执行任务 1 和任务 2,重代码的输出结果来看,任务 1 和任务 2 执行后,for 循环进入阻塞状态,直到任务 1 或者任务 2 结束之后才会 for 才会继续执行任务 3 / 任务 4,并保证同时执行的最多只有两个任务(关于自定义时间格式请参考:Python time 模块).
2.线程池 map 函数使用和 as_completed 方法不同的是:map 方法能保证任务的顺序性,举个例子:如果同时下载 5 个视频,就算第二个视频比第一个视频先下载完成,也会阻塞等待第一个视频下载完成并通知主线程之后,第二个下载完成的视频才回通知主线程,保证按照顺序完成任务,下面举个例子说明一下:
# !usr/bin/env python# -*- coding:utf-8 _*-"""@Author:猿说编程@Blog(个人博客地址): www.codersrc.com@File:Python 线程池 ThreadPoolExecutor.py@Time:2021/05/05 07:37@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!"""from concurrent.futures import ThreadPoolExecutor, as_completedimport time# 参数times用来模拟网络请求的时间def download_video(index):time.sleep(index)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2)urls = [3, 2, 1, 4, 5]for data in executor.map(download_video,urls):print("任务{} down load success".format(data))'''输出结果:download video 2 finished at 2021-05-05 07:10:55download video 3 finished at 2021-05-05 07:10:56任务3 down load success任务2 down load successdownload video 1 finished at 2021-05-05 07:10:56任务1 down load successdownload video 4 finished at 2021-05-05 07:10:00任务4 down load successdownload video 5 finished at 2021-05-05 07:10:01任务5 down load success'''代码分析:重上面的输出结果看来,即便任务 2 比任务 3 先完成,for 循环输出的内容依旧是提示先完成的任务 3 再完成任务 2,根据列表 urls 顺序输出,保证任务的顺序性!
3.线程池 wait 函数使用**wait 方法有点类似线程的 join 方法,能阻塞主线程,直到线程池中的所有的线程都操作完成!**实例代码如下:
【二 Python 线程池 ThreadPoolExecutor】
# !usr/bin/env python# -*- coding:utf-8 _*-"""@Author:猿说编程@Blog(个人博客地址): www.codersrc.com@File:Python 线程池 ThreadPoolExecutor.py@Time:2021/05/05 07:37@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!"""from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETEDimport time# 参数times用来模拟网络请求的时间def download_video(index):time.sleep(2)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2)urls = [1, 2, 3, 4, 5]all_task = [executor.submit(download_video,(url)) for url in urls]wait(all_task,return_when=ALL_COMPLETED)print("main ")'''输出结果:download video 2 finished at 2021-05-05 07:10:22download video 1 finished at 2021-05-05 07:10:22download video 3 finished at 2021-05-05 07:10:24download video 4 finished at 2021-05-05 07:10:24download video 5 finished at 2021-05-05 07:10:26main'''** wait 方法接收 3 个参数,等待的任务序列、超时时间以及等待条件 。等待条件 return_when 默认为 ALL_COMPLETED,表明要等待所有的任务都结束 。可以看到运行结果中,确实是所有任务都完成了,主线程才打印出 main。等待条件还可以设置为 FIRST_COMPLETED,表示第一个任务完成就停止等待 。**三.猜你喜欢
- Python 条件推导式
- Python 列表推导式
- Python 字典推导式
- Python 函数声明和调用
- Python 不定长参数 *argc/**kargcs
- Python 匿名函数 lambda
- Python return 逻辑判断表达式
- Python 字符串/列表/元组/字典之间的相互转换
- Python 局部变量和全局变量
- Python type 函数和 isinstance 函数区别
- Python is 和 == 区别
- Python 可变数据类型和不可变数据类型
- Python 浅拷贝和深拷贝
- Python 文件读写操作
- Python 异常处理
- Python 模块 import
- Python __name__ == ‘__main__’详细解释
- Python 线程创建和传参
- Python 线程互斥锁 Lock
- Python 线程时间 Event
- Python 线程条件变量 Condition
- Python 线程定时器 Timer
- Python 线程信号量 Semaphore
- Python 线程障碍对象 Barrier
- Python 线程队列 Queue – FIFO
- Python 线程队列 LifoQueue – LIFO
- Python 线程优先队列 PriorityQueue
本文由博客 - 猿说编程 猿说编程 发布!
- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
