3种方式实现python多线程并发处理
标签: python奇淫技巧
最优线程数
- Ncpu=CPU的数量
- Ucpu=目标CPU使用率
- W/C=等待时间与计算时间的比率
为保持处理器达到期望的使用率,最优的线程池的大小等于
$$Nthreads=Ncpu*Ucpu*(1+W/C$$
- cpu密集型任务,即$W<<C$,则$W/C≈0$,则$Nthreads=Ncpu*Ucpu$
如果希望CPU利用率为100%,则$Nthreads=Ncpu$
- IO密集型任务,即系统大部分时间在跟I/O交互,而这个时间线程不会占用CPU来处理,即在这个时间范围内,可以由其他线程来使用CPU,因而可以多配置一些线程。
- 混合型任务,二者都占有一定的时间
线城池
对于任务数量不断增加的程序,每有一个任务就生成一个线程,最终会导致线程数量的失控。对于任务数量不端增加的程序,固定线程数量的线程池是必要的。
方法一:使用threadpool模块
threadpool是一个比较老的模块了,支持py2 和 py3 。
import threadpool
import time
def sayhello (a):
print("hello: "+a)
time.sleep(2)
def main():
global result
seed=["a","b","c"]
start=time.time()
task_pool=threadpool.ThreadPool(5)
requests=threadpool.makeRequests(sayhello,seed)
for req in requests:
task_pool.putRequest(req)
task_pool.wait()
end=time.time()
time_m = end-start
print("time: "+str(time_m))
start1=time.time()
for each in seed:
sayhello(each)
end1=time.time()
print("time1: "+str(end1-start1))
if __name__ == '__main__':
main(
方法二:使用concurrent.futures模块
from concurrent.futures import ThreadPoolExecutor
import time
import time
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
ll = []
def sayhello(a):
print("hello: "+a)
ll.append(a)
time.sleep(0.8)
def main():
seed=["a","b","c","e","f","g","h"]
start1=time.time()
for each in seed:
sayhello(each)
end1=time.time()
print("time1: "+str(end1-start1))
start2=time.time()
with ThreadPoolExecutor(2) as executor:
for each in seed:
executor.submit(sayhello,each)
end2=time.time()
print("time2: "+str(end2-start2))
def main2():
seed = ["a", "b", "c", "e", "f", "g", "h"]
executor = ThreadPoolExecutor(max_workers=10)
f_list = []
for each in seed:
future = executor.submit(sayhello, each)
f_list.append(future)
wait(f_list)
print(ll)
print('主线程结束')
def main3():
seed = ["a", "b", "c", "e", "f", "g", "h"]
with ThreadPoolExecutor(max_workers=2) as executor:
f_list = []
for each in seed:
future = executor.submit(sayhello, each)
f_list.append(future)
wait(f_list,return_when='ALL_COMPLETED')
print(ll)
print('主线程结束')
if __name__ == '__main__':
main3()
方法三:使用vthread模块
参考:https://pypi.org/project/vthr...
demo1
import vthread
@vthread.pool(6)
def some(a,b,c):
import time;time.sleep(1)
print(a+b+c)
for i in range(10):
some(i,i,i)
demo2:分组线程池
import vthread
pool_1 = vthread.pool(5,gqueue=1) # open a threadpool with 5 threads named 1
pool_2 = vthread.pool(2,gqueue=2) # open a threadpool with 2 threads named 2
@pool_1
def foolfunc1(num):
time.sleep(1)
print(f"foolstring1, test3 foolnumb1:{num}")
@pool_2
def foolfunc2(num):
time.sleep(1)
print(f"foolstring2, test3 foolnumb2:{num}")
@pool_2
def foolfunc3(num):
time.sleep(1)
print(f"foolstring3, test3 foolnumb3:{num}")
for i in range(10): foolfunc1(i)
for i in range(4): foolfunc2(i)
for i in range(2): foolfunc3(i)
来源:https://segmentfault.com/a/1190000017324613
3种方式实现python多线程并发处理的更多相关文章
- python 多线程两种实现方式,Python多线程下的_strptime问题,
python 多线程两种实现方式 原创 Linux操作系统 作者:杨奇龙 时间:2014-06-08 20:24:26 44021 0 目前python 提供了几种多线程实现方式 thread,t ...
- 3种方式实现Java多线程
java中实现多线程的方法有两种:继承Thread类和实现runnable接口. 1.继承Thread类,重写父类run()方法 public class thread1 extends Thread ...
- 第五种方式,python使用组合来添加类方法和属性(二),以selenium的webdriver为例
组合优点多,但经常比继承需要额外的代码. 上一篇是 介绍装饰器.继承.元类.mixin,四种給类动态添加类属性和方法的四种方式. 此篇介绍直接把被组合的类的属性直接加入到类里面,前面的四个例子很简单, ...
- python 零散记录(五) import的几种方式 序列解包 条件和循环 强调getattr内建函数
用import关键字导入模块的几种方式: #python是自解释的,不必多说,代码本身就是人可读的 import xxx from xxx import xxx from xxx import xx1 ...
- c# 多线程的几种方式
1.什么是线程? 进程作为操作系统执行程序的基本单位,拥有应用程序的资源,进程包含线程,进程的资源被线程共享,线程不拥有资源. 2.前台线程和后台线程的区别? 程序关闭时,后台线程直接关闭,但前台线程 ...
- Java中实现多线程的两种方式之间的区别
Java提供了线程类Thread来创建多线程的程序.其实,创建线程与创建普通的类的对象的操作是一样的,而线程就是Thread类或其子类的实例对象.每个Thread对象描述了一个单独的线程.要产生一个线 ...
- bat批处理执行python 的几种方式
第一种方式:@echo off C: cd C:\Users\administrator\Desktopstart python apidemo.py exit第二种方式: start cmd /K ...
- 命令行运行Python脚本时传入参数的三种方式
原文链接:命令行运行Python脚本时传入参数的三种方式(原文的几处错误在此已纠正) 如果在运行python脚本时需要传入一些参数,例如gpus与batch_size,可以使用如下三种方式. pyth ...
- day-3 python多线程编程知识点汇总
python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...
随机推荐
- Codeforces Gym101606 D.Deranging Hat (2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017))
D Deranging Hat 这个题简直了,本来想的是冒泡排序然后逆着输出来的,后来发现不对,因为题目上求的是最优解,而且冒泡的话,输出结果有的超出10000行了,所以就是把一开始的,排好序的字母标 ...
- Intellij IDEA创建项目
问题:无Java文件 解决方案: 打开file下面的project structure,在main目录下新建java文件,并将java文件设置为 Sources属性 问题:无resouces 解决方案 ...
- BZOJ 4568 [Scoi2016]幸运数字(树链剖分 + 异或线性基)
题目链接 BZOJ 4568 考虑树链剖分+线段树维护每一段区域的异或线性基 对于每个询问,求出该点集的异或线性基.然后求一下这个线性基里面能异或出的最大值即可. #include <bits ...
- 洛谷——P2737 [USACO4.1]麦香牛块Beef McNuggets
https://www.luogu.org/problemnew/show/P2737 题目描述 农夫布朗的奶牛们正在进行斗争,因为它们听说麦当劳正在考虑引进一种新产品:麦香牛块.奶牛们正在想尽一切办 ...
- BZOJ——1601: [Usaco2008 Oct]灌水
http://www.lydsy.com/JudgeOnline/problem.php?id=1601 Time Limit: 5 Sec Memory Limit: 162 MBSubmit: ...
- 支持C++11标准
设置CB下的GCC. Settings->Compiler->Compiler Settings勾选Have g++ follow the C++11 ISO C++ language s ...
- iOS -- SKTransition类
SKTransition类 继承自 NSObject 符合 NSObject(NSObject) 框架 /System/Library/Frameworks/SpriteKit.framewor ...
- word中更改图片和标题之间的垂直距离
word中插入图片后.往往须要给图片加上标题. 你插入图片和给图片插入标题时,word用的是默认的格式给你插入的图片和标题. 假如原来的paragraph是2倍行距.你的图片和标题之间的距离也是2倍行 ...
- Odoo 养猪
阶段 仔猪养成为肉猪 乳猪养成为仔猪 母猪繁殖乳猪 每一个饲养阶段,基本上在同一组笼舍,活动场所:进入到下一饲养阶段才会转换笼舍.在每一个饲养阶段,基本上经历以下过程 饲养 注射疫苗 饲养 投 ...
- sh脚本——#!/bin/bash
#!/bin/bash是指此脚本使用/bin/bash来解释执行. 其中,#!是一个特殊的表示符,其后,跟着解释此脚本的shell路径. bash只是shell的一种,还有很多其它shell,如:sh ...