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 ...
随机推荐
- 2017-12-14python全栈9期第一天第八节之循环语句while
12,while. while 条件: 循环体 无限循环. 终止循环:1,改变条件,使其不成立. 2,break continue
- VirtualBox安装Ubuntu14.04
创建虚拟机 点击 新建(N) 设置虚拟机的名称,类型与版本,如下图所示: 分配虚拟机的内存大小,受PC实际内存影响,暂时设置为2G,如下图所示: 分配虚拟机的硬盘大小,默认即可,如下图所示: 分配虚拟 ...
- Oracle的to_char()函数使用
(1)用作日期转换: to_char(date,'格式'); select to_date('2005-01-01 ','yyyy-MM-dd') from dual; select to_char( ...
- Nullable<DateTime> DateTime? 格式转换问题 tostring()
解决方案: DateTime? dt2 = DateTime.Now; dt2.GetValueOrDefault().ToString("yyyy-MM-dd"); 控制器代码: ...
- 【转载】C# 泛型详解
https://www.cnblogs.com/yueyue184/p/5032156.html
- C#数据库发布与连接
1. 打开相关的服务 在控制面板,打开或关闭Windows特性里面,启动相关的ASP.NET相关服务,并启用IIS Manager 2. 发布应用 3. 添加应用 在Administer tools里 ...
- asp.net写入读取xml的方法
添加命名空间 using System.Xml; 我自己的代码(添加其中的节点) XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(Server.M ...
- 【python小练】0011题
第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights. #word.tx ...
- solr window环境安装配置和管理页面基本使用
solr介绍 来自官网http://lucene.apache.org/solr/解释: Solr is highly reliable, scalable and fault tolerant, p ...
- PHP文件系统管理
文件概念: 第一个是windows的文件,另一个php根据LINUX的文件,两者是有所不同的,我们说的页面基于windows的文件可以是是文件夹(也就是目录)或是文件,而php两者都必须有,它包含目录 ...