8-[多线程] 进程池线程池

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280493.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python 图像识别pytesseract快速设置

一、安装Tesseract 以window安装为例&#xff0c;参考&#xff1a;https://segmentfault.com/a/1190000014086067 note&#xff1a; 使用虚拟环境需要&#xff1a; 在 python 环境&#xff08;或虚拟环境&#xff09; \Lib\site-packages\pytesseract 目录下找到 pytessera…

香港连续25年被评为全球最自由经济体

中新社香港1月25日电 美国智库传统基金会25日在华盛顿发表2019年《经济自由度指数》报告&#xff0c;香港今年再次成为唯一一个总分超过90分的经济体&#xff0c;已连续25年被评价为全球最自由经济体。 报告显示&#xff0c;香港今年的总分为90.2分&#xff08;100分为满分&…

mac 下安装jenkins

2019独角兽企业重金招聘Python工程师标准>>> 平台搭建 Jenkins安装和启动 官网&#xff1a;https://jenkins.io/index.html 下载&#xff1a;http://mirrors.jenkins-ci.org/war/latest/jenkins.war 安装&#xff1a; 依赖于Java环境&#xff0c;首先安装和配置Java…

safari 获取视频流_如何在Safari中将RSS feed和社交媒体合并为一个流

safari 获取视频流Safari allows you to subscribe to RSS feeds and add your social media accounts so you can view them right in the browser, in one universal feed, without the need of any add-on applications or extensions. Safari允许您订阅RSS feed并添加您的社…

pytesseract:opencv预处理图片

一、目的 原始图片用pytesseract识别文字&#xff0c;精准度往往没达到预期。使用opencv处理后&#xff0c;提高识别精准度。处理方法有 a.图片转成白底黑字。 b.截取图片某固定区域。这个很重要&#xff0c;因为图片包含图标或其他形状图形&#xff0c;辨识导致错乱的。 二…

编译安装Centos7.2+Apache2.4.25+PHP7.2.10+Mysql5.6.16

一、编译部署Apache2.4.251、环境准备#设置或停止防火墙&#xff1a; [rootlocalhost ~]# systemctl stop firewalld.service [rootlocalhost ~]# systemctl disable firewalld.service#关闭selinux&#xff1a; 临时关闭&#xff1a; [rootlocalhost ~]# setenforce 0永久关闭…

SDNU 1217 CD收藏——并查集

Description lmh平常爱听歌&#xff0c;所以买了很多的CD来收藏&#xff0c;但是因为平常整理不当&#xff0c;所以忘记了这些CD的歌手是谁。现在他想知道他到底收藏了多少位歌手的专辑&#xff0c;于是他想了一个办法&#xff0c;同时拿出两个CD来听&#xff0c;可以分辨出来是…

国际知名计算机视觉和机器学习软件开源平台OpenCV正式支持龙架构

前言介绍近期&#xff0c;OpenCV开源社区正式合入了对龙架构&#xff08;LoongArch™&#xff09;支持的代码&#xff0c;基于龙架构自主指令系统&#xff0c;优化后的OpenCV性能显著提升。OpenCV是一款跨平台的计算机视觉和机器学习软件平台&#xff0c;在计算机视觉领域广泛使…

优化器--牛顿法总结

---这里记录下一些关于牛顿法来作为优化器的个人笔记 &#xff1a;&#xff09; 关于牛顿法&#xff0c;先不说其中的概念&#xff0c;来简单看一个例子&#xff1f; 不用计算器&#xff0c;如何手动开一个值的平方根&#xff0c;比如计算{sqrt(a) | a4 } &#xff1f; 不用程序…

在命令提示符输出c语言代码_您可以在Windows命令提示符中更改输出缓冲区的大小吗?...

在命令提示符输出c语言代码If you are someone who loves using the Windows Command Prompt, you may have found yourself curious as to why the screen output buffer has such a ‘large’ default size. Can you change it to a smaller (or even larger) size? Today’…

django23:BS4/kindeditor上传图片

BS4 Beautiful Soup&#xff0c;Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。 安装 pip3 install beautifulsoup4 使用 from bs4 import BeautifulSoup#html_doc为网页内容 soup Be…

设计模式——————观察者模式

工厂模式分为简单工厂&#xff0c;工厂和抽象工厂&#xff0c;三种工厂的实现是越来越复杂的。 观察者模式 本质上就是一种订阅/发布的模型&#xff0c;从逻辑上来说就是一对多的依赖关系。 什么意思呢&#xff1f;好比是一群守卫盯着一个囚犯&#xff0c;只要囚犯一有异动&…

SNMP简介

SNMP简介介绍SNMP的定义、目的、版本演进以及受益。 定义简单网络管理协议SNMP&#xff08;Simple Network Management Protocol&#xff09;是广泛应用于TCP/IP网络的网络管理标准协议。SNMP提供了一种通过运行网络管理软件的中心计算机&#xff08;即网络管理工作站&#xff…

详解vue生命周期及每个阶段适合进行的操作

VUE生命周期的四个阶段 create 创建 -------- 创建vue实例并初始化mount 挂载 -------- 把vue实例和视图进行关联update 更新 ------- 监听数据与视图的变化destroy销毁 ------- 销毁实例生命周期 --- 钩子函数 vue为上面的4个大的阶段提供了一个可编程的接口&#xff0c;我们可…

.Net 7 新编译器 ILC 简析

楔子&#xff1a;这个新编译器的全称是ILCompiler。是之前CoreRT项目合并过来的&#xff0c;在.Net 7成熟&#xff0c;并且可以产业化应用。本质&#xff1a;ILC编译器的本质除了构建CLR的所拥有的主要功能&#xff0c;还包含了对LLVM这种意图取代GCC编译器的操作&#xff0c;对…

mac 防止 下载 睡眠_如何暂时防止Mac进入睡眠状态

mac 防止 下载 睡眠Let’s say you start a big download, then go to bed. When you wake up, you realize your Mac went to sleep before finishing its job. Isn’t there some way to stop this? 假设您开始进行大量下载&#xff0c;然后上床睡觉。 当您醒来时&#xff0…

ubuntu安装chrome driver

首先下载Chrome Driver&#xff08;Firefox Driver的安装与该步骤相同&#xff09; 链接&#xff1a; http://chromedriver.storage.googleapis.com/index.html 接下来在控制台&#xff08;terminal&#xff09;上操作一下红色字体的指令&#xff1a; Install Unzipsudo apt-ge…

深入理解Spring异常处理

宜信技术学院1.前言相信我们每个人在SpringMVC开发中&#xff0c;都遇到这样的问题&#xff1a;当我们的代码正常运行时&#xff0c;返回的数据是我们预期格式&#xff0c;比如json或xml形式&#xff0c;但是一旦出现了异常&#xff08;比如&#xff1a;NPE或者数组越界等等&am…

基于React开发范式的思考:写在Lesx发布之际

例子&#xff1a;lesx-example webpack loader: lesx-loader 一些背景 现在前端框架已经呈现出React、Angular、Vue三足鼎立的局势&#xff0c;对于三者的对比以及技术选型的思考与争论也被讨论了非常多&#xff0c;比如知乎上的这个问题&#xff1a;react.js,angular.js,vue.j…