python多线程之threading、ThreadPoolExecutor.map
背景:
(多线程执行同一个函数任务)某个应用场景需要从数据库中取出几十万的数据时,需要对每个数据进行相应的操作。逐个数据处理过慢,于是考虑对数据进行分段线程处理:
方法一:使用threading模块
代码:
# -*- coding: utf-8 -*-
import math
import random
import time
from threading import Thread _result_list = [] def split_df():
# 线程列表
thread_list = []
# 需要处理的数据
_l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 每个线程处理的数据大小
split_count = 2
# 需要的线程个数
times = math.ceil(len(_l) / split_count)
count = 0
for item in range(times):
_list = _l[count: count + split_count]
# 线程相关处理
thread = Thread(target=work, args=(item, _list,))
thread_list.append(thread)
# 在子线程中运行任务
thread.start()
count += split_count # 线程同步,等待子线程结束任务,主线程再结束
for _item in thread_list:
_item.join() def work(df, _list):
"""
每个线程执行的任务,让程序随机sleep几秒
:param df:
:param _list:
:return:
"""
sleep_time = random.randint(1, 5)
print(f'count is {df},sleep {sleep_time},list is {_list}')
time.sleep(sleep_time)
_result_list.append(df) if __name__ == '__main__':
split_df()
print(len(_result_list), _result_list)
测试结果:
方法二:使用ThreadPoolExecutor.map
代码:
# -*- coding: utf-8 -*-
import math
import random
import time
from concurrent.futures import ThreadPoolExecutor def split_list():
# 线程列表
new_list = []
count_list = []
# 需要处理的数据
_l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 每个线程处理的数据大小
split_count = 2
# 需要的线程个数
times = math.ceil(len(_l) / split_count)
count = 0
for item in range(times):
_list = _l[count: count + split_count]
new_list.append(_list)
count_list.append(count)
count += split_count
return new_list, count_list def work(df, _list):
""" 线程执行的任务,让程序随机sleep几秒
:param df:
:param _list:
:return:
"""
sleep_time = random.randint(1, 5)
print(f'count is {df},sleep {sleep_time},list is {_list}')
time.sleep(sleep_time)
return sleep_time, df, _list def use():
new_list, count_list = split_list()
with ThreadPoolExecutor(max_workers=len(count_list)) as t:
results = t.map(work, new_list, count_list) # 或执行如下两行代码
# pool = ThreadPoolExecutor(max_workers=5)
# 使用map的优点是 每次调用回调函数的结果不用手动的放入结果list中
# results = pool.map(work, new_list, count_list) # map返回一个迭代器,其中的回调函数的参数 最好是可以迭代的数据类型,如list;如果有 多个参数 则 多个参数的 数据长度相同;
# 如: pool.map(work,[[1,2],[3,4]],[0,1]]) 中 [1,2]对应0 ;[3,4]对应1 ;其实内部执行的函数为 work([1,2],0) ; work([3,4],1)
# map返回的结果 是 有序结果;是根据迭代函数执行顺序返回的结果
print(type(results))
# 如下2行 会等待线程任务执行结束后 再执行其他代码
for ret in results:
print(ret)
print('thread execute end!') if __name__ == '__main__':
use()
测试结果:
参考链接:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_1103_3days.html
python多线程之threading、ThreadPoolExecutor.map的更多相关文章
- python多线程之Threading
什么是线程? 线程是操作系统内核调度的基本单位,一个进程中包含一个或多个线程,同一个进程内的多个线程资源共享,线程相比进程是“轻”量级的任务,内核进行调度时效率更高. 多线程有什么优势? 多线程可以实 ...
- “死锁” 与 python多线程之threading模块下的锁机制
一:死锁 在死锁之前需要先了解的概念是“可抢占资源”与“不可抢占资源”[此处的资源可以是硬件设备也可以是一组信息],因为死锁是与不可抢占资源有关的. 可抢占资源:可以从拥有他的进程中抢占而不会发生副作 ...
- python多线程之threading模块
threading模块中的对象 其中除了Thread对象以外,还有许多跟同步相关的对象 threading模块支持守护线程的机制 Thread对象 直接调用法 import threading imp ...
- python 线程之 threading(四)
python 线程之 threading(三) http://www.cnblogs.com/someoneHan/p/6213100.html中对Event做了简单的介绍. 但是如果线程打算一遍一遍 ...
- python 线程之 threading(三)
python 线程之 threading(一)http://www.cnblogs.com/someoneHan/p/6204640.html python 线程之 threading(二)http: ...
- python并发编程之threading线程(一)
进程是系统进行资源分配最小单元,线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.进程在执行过程中拥有独立的内存单元,而多个线程共享内存等资源. 系列文章 py ...
- python利用(threading,ThreadPoolExecutor.map,ThreadPoolExecutor.submit) 三种多线程方式处理 list数据
需求:在从银行数据库中取出 几十万数据时,需要对 每行数据进行相关操作,通过pandas的dataframe发现数据处理过慢,于是 对数据进行 分段后 通过 线程进行处理: 如下给出 测试版代码,通过 ...
- python多线程之Condition(条件变量)
#!/usr/bin/env python # -*- coding: utf-8 -*- from threading import Thread, Condition import time it ...
- python多线程之semaphore(信号量)
#!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import random semaphore = ...
随机推荐
- 【转】unity3d优化总结篇
https://blog.csdn.net/weixin_33733810/article/details/94610167 某些技术或建议有些过时,但也值得参考 另外,关于如何设置不同layer的裁 ...
- windos 启动redis服务端与客户端
服务端:1-win+R 打开命令行2-cd至redis目录,例如 G:\Redis63813-输入 redis-server.exe redis.windows.conf观察是否如图1:至此,已成功: ...
- VASP表面计算步骤小结
原文链接:http://blog.sciencenet.cn/blog-478347-374981.html 一.概述 vasp用“slab” 模型来模拟表面体系结构. vasp计算表面的大 ...
- leetcode 34在排序数组中查找元素的第一个和最后一个位置
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { ve ...
- 【html】合并单元格,并居中显示文本
现状: 想要实现的效果: 代码实现: <tr> <td colspan=" align="center">用例失败为0,无测试详情</td ...
- rocketMQ 订阅关系
场景:2 个消费者进程中,创建了 2 个消费者,同属于 1 个消费组,但是订阅了不同的 topic,会因为订阅信息相互覆盖,导致拉不到消息. 原因是 rocketMQ 的订阅关系,是根据 group ...
- SVN的使用和问题解决方法总结
添加仓库之类的很简单,这里就不说了哈...不会的可以问问我,当然百度再快了..嘿嘿 1.从服务器Check Out代码: 2.提交代码: 3.你是不是今天和我一样纠结如何删除已经上传SVN的内容,其实 ...
- Python基础知识思维导图|自学Python指南
微信公众号[软件测试大本营]回复"python",获取50本python精华电子书. 测试/开发知识干货,互联网职场,程序员成长崛起,终身学习. 现在最火的编程语言是什么?答案就是 ...
- Altera DDR2 IP核学习总结1-----------SRAM,DRAM
SRAM,DRAM,SDRAM和DDR2这些芯片详解网上铺天盖地的各种资料都有,这里只是根据个人习惯做一下总结,方便记忆. 详细资料可以参考https://wenku.baidu.com/view/3 ...
- 源码搭建git,并连接github
一.环境 1.下载源码包 https://mirrors.edge.kernel.org/pub/software/scm/git/ 2.安装编译环境 #yum install gcc gcc-c++ ...