Python3-进程池与线程池
进程池与线程池
在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多,这会对服务端主机带来巨大的压力,甚至于不堪重负而瘫痪,于是我们必须对服务端开启的进程数或线程数加以控制,让机器在一个自己可以承受的范围内运行,这就是进程池或线程池的用途,例如进程池,就是用来存放进程的池子,本质还是基于多进程,只不过是对开启进程的数目加上了限制
介绍
官网:https://docs.python.org/dev/library/concurrent.futures.html concurrent.futures模块提供了高度封装的异步调用接口
ThreadPoolExecutor:线程池,提供异步调用
ProcessPoolExecutor: 进程池,提供异步调用
Both implement the same interface, which is defined by the abstract Executor class.
基本方法
、submit(fn, *args, **kwargs)
异步提交任务 、map(func, *iterables, timeout=None, chunksize=)
取代for循环submit的操作 、shutdown(wait=True)
相当于进程池的pool.close()+pool.join()操作
wait=True,等待池内所有任务执行完毕回收完资源后才继续
wait=False,立即返回,并不会等待池内的任务执行完毕
但不管wait参数为何值,整个程序都会等到所有任务执行完毕
submit和map必须在shutdown之前 、result(timeout=None)
取得结果 、add_done_callback(fn)
回调函数
线程池用法
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import os,time,random
def task(n):
print('%s is runing' %os.getpid())
time.sleep(random.randint(,))
return n** if __name__ == '__main__': executor=ProcessPoolExecutor(max_workers=) futures=[]
for i in range():
future=executor.submit(task,i)
futures.append(future)
executor.shutdown(True)
print('+++>')
for future in futures:
print(future.result())
进程程池用法
把ThreadPoolExecutor换成ProcessPoolExecutor,其余用法全部相同
回调函数
可以为进程池或线程池内得每个进程或线程绑定一个函数,该函数在进程或线程的任务执行完毕后自动触发,并接受任务的返回值当作参数,该函数成为回调函数。
提交任务的两种方法:
1、同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,在执行下一行代码,导致程序是串行
2、异步调用:提交完任务后,不用原地等待任务执行完毕
#提交任务的两种方式
#、同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,导致程序是串行执行
#
# from concurrent.futures import ThreadPoolExecutor
# import time
# import random
#
# def la(name):
# print('%s is laing' %name)
# time.sleep(random.randint(,))
# res=random.randint(,)*'#'
# return {'name':name,'res':res}
#
# def weigh(shit):
# name=shit['name']
# size=len(shit['res'])
# print('%s 拉了 《%s》kg' %(name,size))
#
#
# if __name__ == '__main__':
# pool=ThreadPoolExecutor()
#
# shit1=pool.submit(la,'alex').result()
# weigh(shit1)
#
# shit2=pool.submit(la,'wupeiqi').result()
# weigh(shit2)
#
# shit3=pool.submit(la,'yuanhao').result()
# weigh(shit3) #、异步调用:提交完任务后,不地等待任务执行完毕, from concurrent.futures import ThreadPoolExecutor
import time
import random def la(name):
print('%s is laing' %name)
time.sleep(random.randint(,))
res=random.randint(,)*'#'
return {'name':name,'res':res} def weigh(shit):
shit=shit.result()
name=shit['name']
size=len(shit['res'])
print('%s 拉了 《%s》kg' %(name,size)) if __name__ == '__main__':
pool=ThreadPoolExecutor() pool.submit(la,'alex').add_done_callback(weigh) pool.submit(la,'wupeiqi').add_done_callback(weigh) pool.submit(la,'yuanhao').add_done_callback(weigh)
from concurrent.futures import ThreadPoolExecutor
import requests
import time def get(url):
print('GET %s' % url)
response = requests.get(url)
time.sleep()
return {'url': url, 'content': response.text} def parse(res):
res = res.result()
print('%s parse res is %s' % (res['url'], len(res['content']))) if __name__ == '__main__':
urls=[
'http://www.cnblogs.com/linhaifeng',
'https://www.python.org',
'https://www.openstack.org',
] pool = ThreadPoolExecutor() for url in urls:
pool.submit(get, url).add_done_callback(parse)
线程池 回调函数 简单爬网页
Python3-进程池与线程池的更多相关文章
- python3下multiprocessing、threading和gevent性能对比----暨进程池、线程池和协程池性能对比
python3下multiprocessing.threading和gevent性能对比----暨进程池.线程池和协程池性能对比 标签: python3 / 线程池 / multiprocessi ...
- python进程池与线程池
为什么会进行池化? 一切都是为了效率,每次开启进程都会分配一个属于这个进程独立的内存空间,开启进程过多会占用大量内存,系统调度也会很慢,我们不能无限的开启进程. 进程池原来大概如下图 假设有100个任 ...
- Python中的进程池与线程池(包含代码)
Python中的进程池与线程池 引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用su ...
- Python中的进程池与线程池
引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用submit异步调用 异步+回调函数 ...
- python系列之 - 并发编程(进程池,线程池,协程)
需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...
- 第三十八天 GIL 进程池与线程池
今日内容: 1.GIL 全局解释器锁 2.Cpython解释器并发效率验证 3.线程互斥锁和GIL对比 4.进程池与线程池 一.全局解释器锁 1.GIL:全局解释器锁 GIL本质就是一把互斥锁,是夹在 ...
- python并发编程之进程池,线程池,协程
需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...
- 基于concurrent.futures的进程池 和线程池
concurrent.futures:是关于进程池 和 线程池 的 官方文档 https://docs.python.org/dev/library/concurrent.futures.html 现 ...
- GIL锁、进程池与线程池
1.什么是GIL? 官方解释: ''' In CPython, the global interpreter lock, or GIL, is a mutex that prevents multip ...
- python自带的进程池及线程池
进程池 """ python自带的进程池 """ from multiprocessing import Pool from time im ...
随机推荐
- 利用WinRAR命令行压缩文件或文件夹
压缩文件夹winrar.exe a -ag -k -r -s -ibck c:/bak.rar c:/dat/ 压缩多个文件winrar a -ag -ibck bak.rar filename1 f ...
- Hadoop记录-Hadoop集群添加节点和删除节点
1.添加节点 A:新节点中添加账户,设置无密码登陆 B:Name节点中设置到新节点的无密码登陆 C:在Name节点slaves文件中添加新节点 D:在所有节点/etc/hosts文件中增加新节点(所有 ...
- android studio导出apk
在android studio导出的apk分为4种,一种是未签名调试版apk,一种是未签名发行版apk,一种是已签名调试版apk,还有一种是已签名发行版apk.以下将介绍这4种apk如何导出. 一.调 ...
- html body 100%
html body 100% html <div class="header"> </div> <div class="main" ...
- SpringBoot系列: Java应用程序传参和SpringBoot参数文件
===========================向java 程序传参的几种形式:===========================1. 使用 OS 环境变量. 这个不推荐. 2. 使用JVM ...
- Vertica系列: 自动生成Identity 字段值的方法
参考 https://thisdataguy.com/2015/01/05/vertica-some-uses-of-sequences/ 在 vertica 中有三种定义 identity 字段的方 ...
- 服务器中同一个【ip:port】可以多次accept的问题
一.多次bind的问题 服务器的[ip:port]被某套接字绑定成功后,在该绑定解除之前,同一个[ip:port],不能再次被其他套接字绑定,否则绑定失败 二.多次accept的问题 有外来连接时,若 ...
- mini2440开发板jilnk使用
1.安装Setup_JLinkARM_V402d.exe软件 安装完成打开SEGGR J-FLASH ARM,界面如下: 2.用jlink将开发板与pc连接,打开开发板电源,将开关s2拨到nor fl ...
- 三十四、Linux 进程与信号——信号特点、信号集和信号屏蔽函数
34.1 信号特点 信号的发生是随机的,但信号在何种条件下发生是可预测的 进程杠开始启动时,所有信号的处理方式要么默认,要么忽略:忽略是 SIGUSR1 和 SIGUSR2 两个信号,其他都采取默认方 ...
- 【杂】指针,*,&
一个小程序解释指针变量的作用: #include<iostream> #include"cww.h" void cloud(int *); using namespac ...