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,一经查实,立即删除!

相关文章

香港连续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并添加您的社…

编译安装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永久关闭…

国际知名计算机视觉和机器学习软件开源平台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…

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…

mac共享单个磁盘_如何与您的所有设备共享酒店的单个Wi-Fi连接

mac共享单个磁盘Many hotels still limit you to one or two Wi-Fi devices per room–a frustrating limitation, especially when traveling with someone else. Connection restrictions can apply anywhere you have to log into a Wi-Fi network via a portal instead of …

Python FastApi:快速建立docker容器/挂载共享文件夹/导入导出

一、目的 a.快速把原有fastapi代码部署到docker&#xff0c;让docker在server运行。 b.不涉及docker深入设置。 c.使用python第三方lib少或简单。 二、步骤 ps:请提前安装docker 1.新建Dockerfile&#xff0c;放入到项目根目录 a.Dockerfile没有后缀. b.准备好requireme…

PHP-FPM 与 Nginx 的通信机制总结

PHP-FPM 介绍 CGI 协议与 FastCGI 协议 每种动态语言&#xff08; PHP,Python 等&#xff09;的代码文件需要通过对应的解析器才能被服务器识别&#xff0c;而 CGI 协议就是用来使解释器与服务器可以互相通信。PHP 文件在服务器上的解析需要用到 PHP 解释器&#xff0c;再加上对…

Android——监听事件总结

各种监听事件 1.按钮 Button&#xff08;1&#xff09;点击监听btn_1.setOnClickListener(new View.OnClickListener() { &#xff08;2&#xff09;长按监听btn_1.setOnLongClickListener(new View.OnLongClickListener() { 2.单选框 RadioGroupradio_gp.setOnCheckedChangeLi…

ChatGPT 大智近妖,从宇宙人生到手搓光刻机,从哄女朋友到写年终总结我们聊得非常开心,反而让人越来越忧心...

都说 ChatGPT 要干掉程序员&#xff0c;清理搜索引擎&#xff0c;取代Stack Overflow&#xff0c;还能消灭人类&#xff0c;这些有些言过其实了。ChatGPT 的定位是一个人工智能助理&#xff0c;它说&#xff0c;它的主要目的是通过回答用户的问题&#xff0c;为用户提供帮助。在…

如何在Windows Defender中安排扫描

Windows Defender automatically performs background scans during your PC’s idle moments, but doesn’t include an easy way to schedule a full scan. There is a way to do it, though. Windows Defender在PC空闲时自动执行后台扫描&#xff0c;但是没有包括安排完整扫…

复习深入笔记02:魔法方法/cookie,session,token/异常

魔法方法 对象生成 1.先调用__new__方法&#xff0c;生成空对象。控制对象生成。 2.当执行“对象类名&#xff08;namelqz&#xff09;”&#xff0c;触发类的__init__()

比特熊故事汇独家 | .NET 感恩专场

点击上方蓝字关注我们&#xff08;本文阅读时间&#xff1a;15分钟)大家好&#xff01;我是爱吃、爱玩、更爱学习技术&#xff0c;IT界新晋小红人&#xff0c;开发者的好朋友——比特熊&#xff01;比特熊&#xff1a;本期故事汇是.NET专场&#xff0c;今天一次性邀请到DOTNET领…

Ubuntu Core 给物联网提供更多安全支持

开发四年只会写业务代码&#xff0c;分布式高并发都不会还做程序员&#xff1f; Canonical 是 Ubuntu 的一个桌面环境&#xff0c;该公司目前在云服务业务赚到了钱。因为 Ubuntu Core 为嵌入式设备带来了 Ubuntu 18.04 长期支持(LTS)代码库。Ubuntu Core 的镜像大小为 260MB&…

semantic ui要装什么才能使用

作者&#xff1a;呆呆笨笨链接&#xff1a;https://www.zhihu.com/question/32233356/answer/196799506来源&#xff1a;知乎著作权归作者所有。商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处。本答案将以两种方式讲解如何从零开始使用 Semantic-UI&#xff0c;…