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.pswp.cn/news/280493.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280493.shtml
英文地址,請注明出處:http://en.pswp.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…