python-book
  • 目录
  • 第2章 Python基础 (旧版)
    • 2.1 上节拾遗
    • 2.2 二进制
    • 2.3 字符编码
    • 2.4 基本数据类型——数字
    • 2.5 基本数据类型——字符串
    • 2.6 基本数据类型——列表
    • 2.7 基本数据类型——元组
    • 2.8 可变、不可变数据类型和hash
    • 2.9 基本数据类型——字典
    • 2.10 基本数据类型——集合
    • 2.11 collections模块
    • 2.12 本章小结
      • 习题答案
  • 第3章 Python基础—文件操作&函数(旧版)
    • 3.1 上节拾遗
    • 3.2 三元运算
    • 3.3 字符编码转换
    • 3.4 文件处理
    • 3.5 函数
    • 3.6 函数进阶
    • 3.7 生成器&迭代器
    • 3.8 本章小节
      • 习题答案
  • 第4章 Python基础—常用模块(旧版)
    • 4.1 模块、包介绍和相关语法
    • 4.2 time & datetime 模块
    • 4.3 random 模块
    • 4.4 os 模块
    • 4.5 sys 模块
    • 4.6 shutil 模块
    • 4.7 json & pickle 模块
    • 4.8 shelve 模块
    • 4.9 xml 模块
    • 4.10 ConfigParser 模块
    • 4.11 hashlib 模块
    • 4.12 subprocess 模块
    • 4.13 logging 模块
      • python日志重复输出
    • 4.14 re 模块
    • 4.15 软件开发目录规范
    • 4.16 本章小结
      • 习题答案
  • 第5章 面向对象编程设计与开发
    • 面向对象介绍
    • 类、实例、属性、方法详解
    • 5.1 什么是面向对象的程序设计
    • 5.2 类与对象
    • 5.3 属性查找与绑定方法
    • 5.4 小结
    • 5.5 继承与派生
    • 5.6 组合
    • 5.7 抽象类
    • 5.8 多态与多态性
    • 5.9 封装
    • 5.10 绑定方法与非绑定方法
    • 5.11 内置方法
    • 5.11 内置方法(补充)
    • 5.12 元类
    • 5.13 面向对象的软件开发
    • 5.14 领域模型
    • 5.15 异常处理
    • 5.16 本章总结
  • 第6章 网络编程-SOCKET开发
    • 6.1 C/S架构介绍
    • 6.2 TCP/IP 各层详解
    • 6.3 Socket介绍
    • 6.4 Socket代码实例
    • 6.5 粘包现象与解决方案
    • 6.6 通过socket发送文件
    • 6.7 本章总结
  • 第7章 并发编程
    • 7.1 操作系统介绍
      • 附录1:操作系统介绍
    • 7.2 并发编程之多进程
      • 7.2.1 进程理论
      • 7.2.2 开启进程的两种方式
      • 7.2.3 join方法
      • 7.2.4 守护进程
      • 7.2.5 互斥锁
      • 7.2.6 队列
      • 7.2.7 生产者消费者模型
    • 7.3 并发编程之多线程
      • 7.3.1 线程理论
      • 7.3.2 开启线程的两种方式
      • 7.3.3 多线程与多进程的区别
      • 7.3.4 Thread对象的其他属性或方法
      • 7.3.5 守护线程
      • 7.4.6 GIL全局解释器锁
      • 7.4.7 死锁现象与递归锁
      • 7.4.8 信号量,Event,定时器
      • 7.4.9 线程queue
      • 7.4.10 进程池与线程池
    • 7.4 并发编程之协程
      • 7.4.1 协程介绍
      • 7.4.2 greenlet模块
      • 7.4.3 gevent模块
    • 7.5 IO模型
      • 7.5.1 IO模型介绍
      • 7.5.2 阻塞IO
      • 7.5.3 非阻塞IO
      • 7.5.4 多路复用IO
      • 7.5.5 异步IO
      • 7.5.6 IO模型比较分析
      • 7.5.7 selectors模块
    • 7.6 本章小结
  • 第8章 MySQL数据库
    • 8.1 初识数据库
      • 8.1.1 数据库管理软件的由来
      • 8.1.2 数据库概述
      • 8.1.3 mysql安装与基本管理
      • 8.1.4 初识sql语句
    • 8.2 库操作
      • 8.2.1 库的增删改查
    • 8.3 表操作
      • 8.3.1 存储引擎介绍
      • 8.3.2 表的增删改查
      • 8.3.3 数据类型
        • 1 数值类型
        • 2 日期类型
        • 3 字符串类型
        • 4 枚举类型与集合类型
      • 8.3.4 完整性约束
    • 8.4 数据操作
      • 8.4.1 数据的增删改
      • 8.4.2 单表查询
      • 8.4.3 多表查询
    • 8.5 Navicat工具与pymysql模块
      • 8.5.1 图形工具Navicat
      • 8.5.2 pymysql模块
    • 8.6 mysql内置功能
      • 8.6.1 视图
      • 8.6.2 触发器
      • 8.6.3 事务
      • 8.6.4 存储过程
      • 8.6.5 函数
      • 8.6.6 流程控制
    • 8.7 索引原理与慢查询优化
      • 8.7.1 索引原理与慢查询优化(1)
      • 8.7.2 索引原理与慢查询优化(2)
    • 8.8 本章小结
      • 8.8.1 章节作业
  • 第9章 前端开发
    • 9.0 前端内容介绍
      • 前端究竟是个什么鬼?
    • 9.1 HTML
      • 9.1.1 HTML简介
      • 9.1.2 开发环境
      • 9.1.3 HTML标签介绍
      • 9.1.4 HTML文档结构(重点)
      • 9.1.5 HTML注释
      • 9.1.6 head标签相关内容
      • 9.1.7 body标签相关内容(重点)
        • 常用标签一
        • 常用标签二
      • 9.1.8 HTML标签属性
      • 9.1.9 HTML标签分类(重点)
      • 9.1.10 标签嵌套规则(重点)
      • 9.1.11 HTML练习题
    • 9.2 CSS
      • 9.2.1 CSS介绍
      • 9.2.2 CSS语法
      • 9.2.3 CSS引入方式
      • 9.2.4 基本选择器
      • 9.2.5 组合选择器
      • 9.2.6 属性选择器
      • 9.2.7 分组选择器
      • 9.2.8 伪类选择器
      • 9.2.9 伪元素选择器
      • 9.2.10 选择器的优先级(重点)
      • 9.2.11 字体属性
      • 9.2.12 文字属性
      • 9.2.13 背景属性
      • 9.2.14 display属性(重点)
      • 9.2.15 盒模型(重点)
      • 9.2.16 浮动与清除浮动(重点)
      • 9.2.17 background属性(侧重点)
      • 9.2.18 定位(重点)
      • 9.2.19 z-index(重点)
      • 9.2.20 css练习题
    • 9.3 JavaScript
      • 9.3.1 JavaScript简介
      • 9.3.2 ECMAScript 5.0
      • 9.3.3 正则表达式
      • 9.3.4 DOM(重点)
      • 9.3.5 client、offset、scroll系列
      • 9.3.6 定时器
      • 9.3.7 BOM
      • 9.3.8 练习题
    • 9.4 jQuery
      • 9.4.1使用js的一些疼处
      • 9.4.2 js和jquery的区别
      • 9.4.3 jquery文件的引入
      • 9.4.4 jquery选择器用法
      • 9.4.5 jquery对象和DOM对象的转换
      • 9.4.6 jquery的效果
      • 9.4.7 jquery的属性操作
      • 9.4.8 操作input的value值
      • 9.4.9 jquery文档操作
      • 9.4.10 jquery的CSS
      • 9.4.11 jquery的筛选方法
      • 9.4.12 jquery的事件
      • 9.4.13 jquery的Ajax
      • 9.4.14 补充内容
      • 9.4.15 练习题
    • 9.5 Bootstrap
      • 9.5.1 Bootstrap的介绍和响应式@metia媒体查询
      • 9.5.2 Bootstrap的引入和使用
      • 9.5.3 Bootstrap插件的一些常用属性介绍
    • 9.6 前端内容流程导图
  • 第10章 Django
    • 10.1 web应用与http协议
      • 10.1.1 web应用与web框架
    • 10.2 http协议简介
    • 10.3 Django简介
    • 10.4 Django-2的路由层(URLconf)
    • 10.5 Django的视图层
    • 10.6 Django模板层
    • 10.7 Django模型层
      • 模型层一单表操作
      • 模型层二多表操作
    • 10.8 Django组件-cookie与session
    • 10.9 Django组件-forms组件
    • 10.10 Django组件-用户认证
    • 10.11 Django组件-中间件
    • 10.12 Django组件-分页器
    • 10.13 Django与Ajax
    • 10.14习题
  • 第11章 BBS项目(博客系统)
    • 11.1 基于Ajax和用户认证系统的登录验证
    • 11.2 基于Ajax和forms组件的实现注册功能
    • 11.3 系统首页的布局渲染
    • 11.4 个人站点的文章,标签,分类查询
    • 11.5 文章详细页的设计
    • 11.6 点赞与踩灭功能的实现
    • 11.7 评论功能的实现
    • 11.8 基于富文本编辑器框和beautifulSoup模块防止xss攻击
  • 第12章 CRM项目
    • 12.1 权限组件之权限控制
  • 第1章 Python基础(旧版)
    • 1.1 编程语言介绍
    • 1.2 Python介绍
    • 1.3 Python安装
    • 1.4 第一个Python程序
    • 1.5 变量
    • 1.6 程序交互
    • 1.7 基本数据类型
    • 1.8 格式化输出
    • 1.9 基本运算符
    • 1.10 流程控制之 if ... else
    • 1.11 流程控制之 循环
    • 1.12 开发工具IDE
    • 1.13 本章小节
      • 习题答案
    • 1.14 Python开发规范指南
      • 1.14.1 Python风格规范
      • 1.14.2 Python语言规范
  • 第1章 Python基础语法(new)
    • 1.1 编程语言介绍与分类
    • 1.2 Python介绍、发展趋势
    • 1.3 Python环境安装
    • 1.4 开发你的第一个Python程序
    • 1.5 选择最好用的PyCharm IDE
    • 1.6 变量
    • 1.7 注释
    • 1.8 基本数据类型
    • 1.9 读取用户指令
    • 1.10 格式化打印
    • 1.11 运算符
    • 1.12 流程控制之if...else
    • 1.13 流程控制之while循环
    • 1.14 本章练习题&作业
  • 第2章 Python基础-数据类型和文件操作(new)
    • 2.1 上章补充-Bytes类型
  • 第3章 Python基础-函数编程(new)
  • 第4章 Python基础 常用模块(new)
Powered by GitBook
On this page
  • 一 进程池与线程池
  • 二 进程池
  • 三 线程池
  • 四 map方法
  • 五 回调函数

Was this helpful?

  1. 第7章 并发编程
  2. 7.3 并发编程之多线程

7.4.10 进程池与线程池

  • 掌握进程池与线程池的用法

  • 掌回调函数

本节时长需控制在30分钟内

一 进程池与线程池

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

介绍

官网: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.

基本方法

1、submit(fn, *args, **kwargs)
异步提交任务

2、map(func, *iterables, timeout=None, chunksize=1) 
取代for循环submit的操作

3、shutdown(wait=True) 
相当于进程池的pool.close()+pool.join()操作
wait=True,等待池内所有任务执行完毕回收完资源后才继续
wait=False,立即返回,并不会等待池内的任务执行完毕
但不管wait参数为何值,整个程序都会等到所有任务执行完毕
submit和map必须在shutdown之前

4、result(timeout=None)
取得结果

5、add_done_callback(fn)
回调函数

二 进程池

介绍

The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.

class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None)
An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised.

用法

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

import os,time,random
def task(n):
    print('%s is runing' %os.getpid())
    time.sleep(random.randint(1,3))
    return n**2

if __name__ == '__main__':

    executor=ProcessPoolExecutor(max_workers=3)

    futures=[]
    for i in range(11):
        future=executor.submit(task,i)
        futures.append(future)
    executor.shutdown(True)
    print('+++>')
    for future in futures:
        print(future.result())

三 线程池

介绍

ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.
class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')
An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.

Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor.

New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.

用法

把ProcessPoolExecutor换成ThreadPoolExecutor,其余用法全部相同

四 map方法

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

import os,time,random
def task(n):
    print('%s is runing' %os.getpid())
    time.sleep(random.randint(1,3))
    return n**2

if __name__ == '__main__':

    executor=ThreadPoolExecutor(max_workers=3)

    # for i in range(11):
    #     future=executor.submit(task,i)

    executor.map(task,range(1,12)) #map取代了for+submit

五 回调函数

可以为进程池或线程池内的每个进程或线程绑定一个函数,该函数在进程或线程的任务执行完毕后自动触发,并接收任务的返回值当作参数,该函数称为回调函数

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from multiprocessing import Pool
import requests
import json
import os

def get_page(url):
    print('<进程%s> get %s' %(os.getpid(),url))
    respone=requests.get(url)
    if respone.status_code == 200:
        return {'url':url,'text':respone.text}

def parse_page(res):
    res=res.result()
    print('<进程%s> parse %s' %(os.getpid(),res['url']))
    parse_res='url:<%s> size:[%s]\n' %(res['url'],len(res['text']))
    with open('db.txt','a') as f:
        f.write(parse_res)


if __name__ == '__main__':
    urls=[
        'https://www.baidu.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://help.github.com/',
        'http://www.sina.com.cn/'
    ]

    p=ProcessPoolExecutor(3)
    for url in urls:
        p.submit(get_page,url).add_done_callback(parse_page) #parse_page拿到的是一个future对象obj,需要用obj.result()拿到结果
Previous7.4.9 线程queueNext7.4 并发编程之协程

Last updated 5 years ago

Was this helpful?