进程池与线程池

在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多,这会对服务端主机带来巨大的压力,甚至于不堪重负而瘫痪,于是我们必须对服务端开启的进程数或线程数加以控制,让机器在一个自己可以承受的范围内运行,这就是进程池或线程池的用途,例如进程池,就是用来存放进程的池子,本质还是基于多进程,只不过是对开启进程的数目加上了限制

介绍

官网: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-进程池与线程池的更多相关文章

  1. python3下multiprocessing、threading和gevent性能对比----暨进程池、线程池和协程池性能对比

    python3下multiprocessing.threading和gevent性能对比----暨进程池.线程池和协程池性能对比   标签: python3 / 线程池 / multiprocessi ...

  2. python进程池与线程池

    为什么会进行池化? 一切都是为了效率,每次开启进程都会分配一个属于这个进程独立的内存空间,开启进程过多会占用大量内存,系统调度也会很慢,我们不能无限的开启进程. 进程池原来大概如下图 假设有100个任 ...

  3. Python中的进程池与线程池(包含代码)

    Python中的进程池与线程池 引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用su ...

  4. Python中的进程池与线程池

    引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用submit异步调用 异步+回调函数 ...

  5. python系列之 - 并发编程(进程池,线程池,协程)

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

  6. 第三十八天 GIL 进程池与线程池

    今日内容: 1.GIL 全局解释器锁 2.Cpython解释器并发效率验证 3.线程互斥锁和GIL对比 4.进程池与线程池 一.全局解释器锁 1.GIL:全局解释器锁 GIL本质就是一把互斥锁,是夹在 ...

  7. python并发编程之进程池,线程池,协程

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

  8. 基于concurrent.futures的进程池 和线程池

    concurrent.futures:是关于进程池 和 线程池 的 官方文档 https://docs.python.org/dev/library/concurrent.futures.html 现 ...

  9. GIL锁、进程池与线程池

    1.什么是GIL? 官方解释: ''' In CPython, the global interpreter lock, or GIL, is a mutex that prevents multip ...

  10. python自带的进程池及线程池

    进程池 """ python自带的进程池 """ from multiprocessing import Pool from time im ...

随机推荐

  1. Java概念、语法和变量基础整理

    Java概述 J2SE:  Java 2 Platform Standard Edition( 2005年之后更名为Java SE ).包含构成Java语言核心的类 J2EE: Java 2 Plat ...

  2. 设计模式_策略模式_在Spring中的应用

    一.理论 在spring中经常有读取配置文件的需求,这里就会用到一个Spring提供的Resource接口 Resource 接口是具体资源访问策略的抽象,也是所有资源访问类所实现的接口.Resour ...

  3. Spring boot 使用多个RedisTemplate

    问题描述 想在一个JAVA Class 向同一个Redis实例的不同 dbindex 写入数据,非常类似于StackOverflowe上的[How can select dbIndex when I ...

  4. new

    Android支持插件库,可以是由C/C++开发的JNI形式,也可以是由java代码开发的jar形式(也可以是android封包完成的apk文件).加载jar插件的方式可以分为 1.静态加载2.动态加 ...

  5. extjs.net Combox赋值

    1.直接赋值 ].Rows) //遍历获取两个值 { Ext.Net.ListItem listItem = new Ext.Net.ListItem(); //每次创建一个Ext.Net.ListI ...

  6. LINQ to SQL 中 Concat、Union、Intersect、Except 方法的使用

    Ø  前言 LINQ to SQL 中需要对两个或多个数据集进行操作,比如:合并.取交集等,主要使用下面四个方法,这四个方法都是 System.Linq.IQueryable<out T> ...

  7. MQTT学习笔记

    因为工作需要,了解了一下MQTT.顺便记下来,现在还不会用. 一.概述 MQTT(Message Queuing Telemetyr Transport  消息队列遥测传输协议):基于发布/订阅(Pu ...

  8. 可由inetd启动的协议无关时间获取服务器程序

    #include <time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> ...

  9. write命令帮助文档(ubuntu 18.04)

    WRITE() BSD General Commands Manual WRITE() NAME write — send a message to another user SYNOPSIS wri ...

  10. 二十九、Linux 进程与信号——minishell(2)

    编程内容: 1.完成  echo env export 命令 2.完成前后台进程 3.完成重定向 完整代码如下: 29.1 主函数.通用头文件和Makefile 29.1.1 主函数 mshell_m ...