1、为甚需要进程池,线程池

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

   

2、基本方法

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)    回调函数

  

3、进程池

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 ProcessPoolExecutor, ThreadPoolExecutor
import os
import timedef task(name):print('%s is running 《pid: %s》' % (name, os.getpid()))time.sleep(2)if __name__ == '__main__':# p = Process(target=task, args=('子',))# p.start
pool = ProcessPoolExecutor(4)  # 进程池max_workers:4个for i in range(10):     # 总共执行10次,每次4个进程的执行pool.submit(task, '子进程%s' % i)print('主')

4、线程池

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.

5、map函数:取代了for+submit

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutorimport os,time,random
def task(n):print('%s is runing' %os.getpid())time.sleep(random.randint(1,3))return n**2if __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

6、异步调用与回调机制

(1)提交任务的两种方式

# 提交任务的两种方式
# 1、同步调用     提交完任务后,拿到结果,再执行下一行代码,导致程序是串行执行
# 2、异步调用    提交完任务后,不用等待任务执行完毕

  

(2)同步调用

from concurrent.futures import ThreadPoolExecutor
import time
import random# 吃饭
def eat(name):print('%s is eat' % name)time.sleep(random.randint(1,5))ret = random.randint(7, 13) * '#'return {'name': name, 'ret': ret}# 称重
def weight(body):name = body['name']size = len(body['ret'])print('%s 现在的体重是%s' %(name, size))if __name__ == '__main__':pool = ThreadPoolExecutor(15)rice1 = pool.submit(eat, 'alex').result()   # 取得结果       # 执行函数eatweight(rice1)                                               # 执行函数weight
rice2 = pool.submit(eat, 'jack').result()   weight(rice2)rice3 = pool.submit(eat, 'tom').result()    weight(rice3)


(2)同步调用2

  (3)回调函数

  

  

  (4)是钩子函数?

钩子函数是Windows消息处理机制的一部分,通过设置“钩子”,应用程序可以在系统级对所有消息、事件进行过滤,访问在正常情况下无法访问的消息。钩子的本质是一段用以处理系统消息的程序,通过系统调用,把它挂入系统 --- 百度百科的定义

    

对于前端来说,钩子函数就是指再所有函数执行前,我先执行了的函数,即 钩住 我感兴趣的函数,只要它执行,我就先执行。此概念(或者说现象)跟AOP(面向切面编程)很像

  

7.线程池爬虫应用

(1)requests模块

import requests# 输入网址,得到网址的源代码

response = requests.get('http://www.cnblogs.com/venicid/p/8923096.html')
print(response)    # 输出<Response [200]>
print(response.text)    # 以文本格式输出

 

(2)线程池爬虫

import requests
import time
from concurrent.futures import ThreadPoolExecutor# 输入网址,得到网址的源代码
def get_code(url):print('GET ', url)response = requests.get(url)time.sleep(3)code = response.textreturn {'url': url, 'code': code}# 打印源代码的长度
def print_len(ret):ret = ret.result()url = ret['url']code_len = len(ret['code'])print('%s length is %s' % (url, code_len))if __name__ == '__main__':url_list = ['http://www.cnblogs.com/venicid/default.html?page=2','http://www.cnblogs.com/venicid/p/8747383.html','http://www.cnblogs.com/venicid/p/8923096.html',]pool = ThreadPoolExecutor(2)for i in url_list:pool.submit(get_code, i).add_done_callback(print_len)pool.map(get_code, url_list)

转载于:https://www.cnblogs.com/venicid/p/8923528.html

8-[多线程] 进程池线程池相关推荐

  1. python多线程队列和池_Python3 从零单排28_线程队列进程池线程池

    1.线程队列 线程队列有三种:先进先出,后进先出,按优先级进出,具体如下: 1 importqueue2 3 #先进先出 4 q = queue.Queue(3)5 6 q.put(1)7 q.put ...

  2. 递归锁、信号量、GIL锁、基于多线程的socket通信和进程池线程池

    递归锁.信号量.GIL锁.基于多线程的socket通信和进程池线程池 递归锁 死锁现象:是指两个或两个以上的进程和线程因抢夺计算机资源而产生的一种互相等待的现象 from threading impo ...

  3. python线程池并发_python 并发编程多线程之进程池/线程池

    一.验证GIL锁的存在 Python在设计之初就考虑到要在主循环中,同时只有一个线程在执行.虽然 Python 解释器中可以"运行"多个线程,但在任意时刻只有一个线程在解释器中运行 ...

  4. python 协程池gevent.pool_进程池\线程池,协程,gevent

    目录 1. 进程池与线程池 2. 协程 3. gevent 4. 单线程下实现并发的套接字通信 首先写一个基于多线程的套接字 服务端: from socket import * from thread ...

  5. python并发编程-进程池线程池-协程-I/O模型-04

    目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...

  6. 第十章_多线程(2)_线程池原子性并发工具类

    目录 一.线程池 1 - 线程状态 2 - 线程池 3 - Executors线程池 二.Volatile 三.原子性 四.并发工具类 1 - 并发工具类-Hashtable 2 - 并发工具类-Co ...

  7. 学习笔记(33):Python网络编程并发编程-进程池线程池

    立即学习:https://edu.csdn.net/course/play/24458/296451?utm_source=blogtoedu 进程池与线程池: 一般应用在网站上,进程池或线程池最大的 ...

  8. Java多线程系列--“JUC线程池”06之 Callable和Future

    转载自  Java多线程系列--"JUC线程池"06之 Callable和Future Callable 和 Future 简介 Callable 和 Future 是比较有趣的一 ...

  9. linux下c语言线程传参数,【linux】C语言多线程中运行线程池,在线程池中运行线程池,,传递的结构体参数值为空/NULL/0...

    C语言多线程中运行线程池,在线程池中运行线程池,,传递的结构体参数值为空/NULL/0 本贴问题,之前已经提问过一次,当时已经解决了,原贴在这里https://segmentfault.com/q/1 ...

  10. Java多线程案例之线程池

    文章目录 一. 线程池概述 1. 什么是线程池 2. Java标准库提供的线程池 二. 线程池的简单实现 一. 线程池概述 1. 什么是线程池 线程池和和字符串常量池, 数据库连接池一样, 都是为了提 ...

最新文章

  1. python威氏符号秩次检验(Wilcoxon Signed-Rank Test)
  2. Spring Boot——游戏成就系统设计DEMO
  3. C++学习笔记-----在一个构造函数中调用另一个构造函数
  4. 【NoSQL】NoSQL入门和概述 - 笔记
  5. C#设计模式(5)-Factory Method Pattern
  6. java三层架构项目事例_三层架构实例
  7. 【转】Pro Android学习笔记(一):Android 平台 2013.6.4
  8. WordPress 5.1.1 发布,修复 CSRF 漏洞
  9. 从二分逼近领略计算科学的魅力
  10. 大型企业能源管理系统的设计与应用
  11. python itchat库学习笔记 + 微信防撤回实现详解(超详细)(已上传)
  12. php 一次性动态口令,一次性口令 (OTP) 动态口令身份认证
  13. html页面国际化之谷歌翻译js实践,支持通过判断浏览器语言自动将中文翻译成英文
  14. css 剪辑图片_css如何截取图片?
  15. linux绝育玩客云_绝育老母鸡(玩客云)PT下载补充。如何过新手考核
  16. Conflux 进阶课 | 详解CIP-37(上)
  17. 起始点的跳变、冲激函数匹配法
  18. 宁波大学c语言理论考试试题科目一,汽车类科目一考试题库安全法律、法规跟规节.doc...
  19. PHP 银联接口 商户测试
  20. 全球及中国差速器总成行业发展前景规划与投资模式分析报告2021年版

热门文章

  1. linux php cli 太多,【linux】php cli 处理能力到底有多强?
  2. java long类型转string_JavaSE的学习——数据类型
  3. git版本回退命令_Git学习版本回退和管理文件的修改及删除操作
  4. TreeMap是按照key的字典顺序来排序
  5. C# Android wifi控制灯,求助如何在基于安卓通过WiFi与Arduino通信,实现对LED灯的控制。...
  6. vscode工作区是什么意思_空压机的容积流量和工作压力是什么意思?
  7. linux下搭建vsftp锁定根目录,Linux服务搭建之vsftp
  8. apk私钥_获取APK证书MD5、SHA1、SHA256等秘钥
  9. api zabbix 拓扑图 获取_zabbix网络拓扑图配置-Maps(示例代码)
  10. python合法变量类型_Python 变量类型