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场景下,也不再是并行方式运 ...
随机推荐
- LaTeX 如何在文档的侧面插入图片实现"绕排"?
https://www.zhihu.com/question/26837705 https://blog.csdn.net/u012856866/article/details/70305834
- Codeforces635C XOR Equation【数学】
题目链接: http://codeforces.com/contest/635/problem/C 题意: 给定两个数的和s及异或x,求两个数的可能情况. 分析: 我们有公式a+b=a& b∗ ...
- [Python Cookbook] Numpy Array Manipulation
1. Reshape: The np.reshape() method will give a new shape to an array without changing its data. Not ...
- House Robber(动态规划)
思路: 代码: class Solution { public: int rob(vector<int> &num) { ; int size=num.size(); ) ]; v ...
- Nginx+keepalived双机热备(主主模式)
IP说明: master机器(master-node):10.0.0.5/172.16.1.5 VIP1:10.0.0.3slave机器(slave-node): 10.0.0.6/172.16. ...
- bzoj 4921: [Lydsy六月月赛]互质序列
4921: [Lydsy六月月赛]互质序列 Time Limit: 1 Sec Memory Limit: 256 MBSubmit: 188 Solved: 110[Submit][Status ...
- spring版本不兼容JDK问题
在实验书上Spring项目的时候出现一个问题,导入包和使用注释的时候eclipse出现报错. 导入包报错:The import org cannot be resolved 注释报错:componen ...
- 天啦噜!原来Chrome自带的开发者工具还能这么用!
作者:余博伦链接:https://zhuanlan.zhihu.com/p/22665710来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. Chrome自带开发者工具. ...
- curl如何发送json数据?如何发送form数据?python的restfull又该如何获取这些数据?
1.python使用flask+flask_restfull框架写的api接口,做为服务 2.curl 做为客户端发送数据 from flask import request curl发送json的方 ...
- 关于Gradle配置的小结
前言 使用 Android Studio 来开发 Android 工程的过程中,接触 Gradle 是不可避免的,比如配置签名.引入依赖等.那么 Gradle 到底是什么东西呢? Gradle 是一个 ...