标签: 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多线程并发处理的更多相关文章

  1. python 多线程两种实现方式,Python多线程下的_strptime问题,

    python 多线程两种实现方式 原创 Linux操作系统 作者:杨奇龙 时间:2014-06-08 20:24:26  44021  0 目前python 提供了几种多线程实现方式 thread,t ...

  2. 3种方式实现Java多线程

    java中实现多线程的方法有两种:继承Thread类和实现runnable接口. 1.继承Thread类,重写父类run()方法 public class thread1 extends Thread ...

  3. 第五种方式,python使用组合来添加类方法和属性(二),以selenium的webdriver为例

    组合优点多,但经常比继承需要额外的代码. 上一篇是 介绍装饰器.继承.元类.mixin,四种給类动态添加类属性和方法的四种方式. 此篇介绍直接把被组合的类的属性直接加入到类里面,前面的四个例子很简单, ...

  4. python 零散记录(五) import的几种方式 序列解包 条件和循环 强调getattr内建函数

    用import关键字导入模块的几种方式: #python是自解释的,不必多说,代码本身就是人可读的 import xxx from xxx import xxx from xxx import xx1 ...

  5. c# 多线程的几种方式

    1.什么是线程? 进程作为操作系统执行程序的基本单位,拥有应用程序的资源,进程包含线程,进程的资源被线程共享,线程不拥有资源. 2.前台线程和后台线程的区别? 程序关闭时,后台线程直接关闭,但前台线程 ...

  6. Java中实现多线程的两种方式之间的区别

    Java提供了线程类Thread来创建多线程的程序.其实,创建线程与创建普通的类的对象的操作是一样的,而线程就是Thread类或其子类的实例对象.每个Thread对象描述了一个单独的线程.要产生一个线 ...

  7. bat批处理执行python 的几种方式

    第一种方式:@echo off C: cd C:\Users\administrator\Desktopstart python apidemo.py exit第二种方式: start cmd /K ...

  8. 命令行运行Python脚本时传入参数的三种方式

    原文链接:命令行运行Python脚本时传入参数的三种方式(原文的几处错误在此已纠正) 如果在运行python脚本时需要传入一些参数,例如gpus与batch_size,可以使用如下三种方式. pyth ...

  9. day-3 python多线程编程知识点汇总

    python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...

随机推荐

  1. 51Nod 1239 欧拉函数前n项和 杜教筛

    http://www.51nod.com/Challenge/Problem.html#!#problemId=1239 AC代码 #include <bits/stdc++.h> #de ...

  2. Codeforces Round #317 [AimFund Thanks-Round] (Div. 2) Array 模拟

    题目链接:http://codeforces.com/contest/572/problem/A 题意 就给你两个数组,问你能不能从A数组中取出k个,B数组中取出m个,使得这k个都大于这m个. 题解 ...

  3. Codeforces Round #295 (Div. 1) C. Pluses everywhere

    昨天ZZD大神邀请我做一道题,说这题很有趣啊. 哇,然后我被虐了. Orz ZZD 题目大意: 你有一个长度为n的'0-9'串,你要在其中加入k个'+'号,每种方案就会形成一个算式,算式算出来的值记做 ...

  4. kafka技术分享02--------kafka入门

    kafka技术分享02--------kafka入门 1. 消息系统 ​ 所谓的Messaging System就是一组规范,企业利用这组规范在不同的系统之间传递语义准确对的消息,实现松耦合的异步数据 ...

  5. go 协程与主线程强占运行

    最近在学习了Go 语言 ,  正好学习到了 协程这一块 ,遇到了困惑的地方.这个是go语言官方文档 . 在我的理解当中是,协程只能在主线程释放时间片后才会经过系统调度来运行协程,其实正确的也确实是这样 ...

  6. CUDA 实现JPEG图像解码为RGB数据

    了解JPEG数据格式的人应该easy想到.其对图像以8*8像素块大小进行切割压缩的方法非常好用并行处理的思想来实现.而其实英伟达的CUDA自v5.5開始也提供了JPEG编解码的演示样例.该演示样例存储 ...

  7. [MFC]选择目录对话框和选择文件对话框 [转]

      在MFC编程中经常会需要用到选择目录和选择文件的界面,以下总结一下本人常用的这两种对话框的生成方法: 选择目录对话框 {    char szPath[MAX_PATH];     //存放选择的 ...

  8. 全文索引-lucene,solr,nutch,hadoop之nutch与hadoop

    全文索引-lucene.solr.nutch,hadoop之lucene 全文索引-lucene.solr,nutch,hadoop之solr 我在去年的时候,就想把lucene,solr.nutch ...

  9. centos 升级内核失败回救

    在升级 centos6.3上使用, yum -y update  ... 灾难出现了!!! 解决方法: 1. 在机器启动的时候, 按F1, 会出现选择内核,选一个原来的. 2. vim /etc/gr ...

  10. Android API Guides---Services

    服务 在该文献 基础 声明在清单服务 创建一个启动的服务 扩展IntentService类 扩展服务类 启动服务 停止服务 创建绑定服务 将通知发送给用户 执行在前台服务 管理服务生命周期 实施生命周 ...