欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中ThreadPoolExecutor線程池和ProcessPoolExecutor進程池

 更新時間:2022年06月16日 16:05:42   作者:??HZ在掘金????  
這篇文章主要介紹了python中ThreadPoolExecutor線程池和ProcessPoolExecutor進程池,文章圍繞主題相關資料展開詳細的內容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下

1、ThreadPoolExecutor多線程

<1>為什么需要線程池呢?

  • 對于io密集型,提高執(zhí)行的效率。
  • 線程的創(chuàng)建是需要消耗系統(tǒng)資源的。

所以線程池的思想就是:每個線程各自分配一個任務,剩下的任務排隊等待,當某個線程完成了任務的時候,排隊任務就可以安排給這個線程繼續(xù)執(zhí)行。

<2>標準庫concurrent.futures模塊

它提供了ThreadPoolExecutor和ProcessPoolExecutor兩個類,
分別實現(xiàn)了對threading模塊和multiprocessing模塊的進一步抽象。

不僅可以幫我們自動調度線程,還可以做到:

  • 主線程可以獲取某一個線程(或者任務)的狀態(tài),以及返回值
  • 當一個線程完成的時候,主線程能夠立即知道
  • 讓多線程和多進程的編碼接口一致

<3>簡單使用

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import time

# 參數(shù)times用來模擬網(wǎng)絡請求時間
def get_html(times):
    print("get page {}s finished".format(times))
   return times
# 創(chuàng)建線程池
# 設置線程池中最多能同時運行的線程數(shù)目,其他等待
executor = ThreadPoolExecutor(max_workers=2)
# 通過submit函數(shù)提交執(zhí)行的函數(shù)到線程池中,submit函數(shù)立即返回,不阻塞
# task1和task2是任務句柄
task1 = executor.submit( get_html, (2) )
task2 = executor.submit( get_html, (3) )

# done()方法用于判斷某個任務是否完成,bool型,完成返回True,沒有完成返回False
print( task1.done() )
# cancel()方法用于取消某個任務,該任務沒有放到線程池中才能被取消,如果已經(jīng)放進線程池子中,則不能被取消
# bool型,成功取消了返回True,沒有取消返回False
print( task2.cancel() )
# result()方法可以獲取task的執(zhí)行結果,前提是get_html()函數(shù)有返回值
print( task1.result() )
print( task2.result() )
# 結果:
# get page 3s finished
# get page 2s finished
# True
# False

# 2
# 3

ThreadPoolExecutor類在構造實例的時候,傳入max_workers參數(shù)來設置線程池中最多能同時運行的線程數(shù)目
使用submit()函數(shù)來提交線程需要執(zhí)行任務(函數(shù)名和參數(shù))到線程池中,并返回該任務的句柄,

注意:submit()不是阻塞的,而是立即返回。

通過submit()函數(shù)返回的任務句柄,能夠使用done()方法判斷該任務是否結束,使用cancel()方法來取消,使用result()方法可以獲取任務的返回值,查看內部代碼,發(fā)現(xiàn)該方法是阻塞的

<4>as_completed(一次性獲取所有的結果)

上面雖然提供了判斷任務是否結束的方法,但是不能在主線程中一直判斷,有時候我們是得知某個任務結束了,就去獲取結果,而不是一直判斷每個任務有沒有結束。這時候就可以使用as_completed方法一次取出所有任務的結果。

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor, as_completed
import time

# 參數(shù)times用來模擬網(wǎng)絡請求時間
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times

# 創(chuàng)建線程池子
# 設置最多2個線程運行,其他等待
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
# 一次性把所有的任務都放進線程池,得到一個句柄,但是最多只能同時執(zhí)行2個任務
all_task = [ executor.submit(get_html,(each_url)) for each_url in urls ] 

for future in as_completed( all_task ):
    data = future.result()
    print("in main:get page {}s success".format(data))

# 結果
# get page 2s finished
# in main:get page 2s success
# get page 3s finished
# in main:get page 3s success
# get page 4s finished
# in main:get page 4s success
# 從結果可以看到,并不是先傳入哪個url,就先執(zhí)行哪個url,沒有先后順序

<5>map()方法

除了上面的as_completed()方法,還可以使用execumap方法。但是有一點不同,使用map方法,不需提前使用submit方法,
map方法與python標準庫中的map含義相同,都是將序列中的每個元素都執(zhí)行同一個函數(shù)。上面的代碼就是對urls列表中的每個元素都執(zhí)行get_html()函數(shù),并分配各線程池??梢钥吹綀?zhí)行結果與上面的as_completed方法的結果不同,輸出順序和urls列表的順序相同,就算2s的任務先執(zhí)行完成,也會先打印出3s的任務先完成,再打印2s的任務完成

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor,as_completed
import time
# 參數(shù)times用來模擬網(wǎng)絡請求時間
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
# 創(chuàng)建線程池子
# 設置最多2個線程運行,其他等待
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
for result in executor.map(get_html, urls):
    print("in main:get page {}s success".format(result))

結果:

 get page 2s finished
 get page 3s finished
 in main:get page 3s success
 in main:get page 2s success
 get page 4s finished
 in main:get page 4s success

<6>wait()方法

wait方法可以讓主線程阻塞,直到滿足設定的要求。wait方法接收3個參數(shù),等待的任務序列、超時時間以及等待條件。
等待條件return_when默認為ALL_COMPLETED,表明要等待所有的任務都借宿??梢钥吹竭\行結果中,確實是所有任務都完成了,主線程才打印出main,等待條件還可以設置為FIRST_COMPLETED,表示第一個任務完成就停止等待。

超時時間參數(shù)可以不設置:

wait()方法和as_completed(), map()沒有關系。不管你是用as_completed(),還是用map()方法,你都可以在執(zhí)行主線程之前使用wait()。
as_completed()和map()是二選一的。

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED
import time
# 參數(shù)times用來模擬網(wǎng)絡請求時間
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
   
# 創(chuàng)建線程池子
# 設置最多2個線程運行,其他等待
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
all_task = [executor.submit(get_html,(url)) for url in urls]
wait(all_task,return_when=ALL_COMPLETED)
print("main")
# 結果
# get page 2s finished
# get page 3s finished
# get page 4s finished
# main

2、ProcessPoolExecutor多進程

<1>同步調用方式: 調用,然后等返回值,能解耦,但是速度慢

import datetime
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import current_thread
import time, random, os
import requests
def task(name):
    print('%s %s is running'%(name,os.getpid()))
    #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    
if __name__ == '__main__':
    p = ProcessPoolExecutor(4)  # 設置
    
    for i in range(10):
        # 同步調用方式,不僅要調用,還要等返回值
        obj = p.submit(task, "進程pid:")  # 傳參方式(任務名,參數(shù)),參數(shù)使用位置或者關鍵字參數(shù)
        res = obj.result()
    p.shutdown(wait=True)  # 關閉進程池的入口,等待池內任務運行結束
    print("主")
################
################
# 另一個同步調用的demo
def get(url):
    print('%s GET %s' % (os.getpid(),url))
    time.sleep(3)
    response = requests.get(url)
    if response.status_code == 200:
        res = response.text
    else:
        res = "下載失敗"
    return res  # 有返回值

def parse(res):
    time.sleep(1)
    print("%s 解析結果為%s" %(os.getpid(),len(res)))

if __name__ == "__main__":
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',
    ]
    p=ProcessPoolExecutor(9)
    l=[]
    start = time.time()
    for url in urls:
        future = p.submit(get,url)  # 需要等結果,所以是同步調用
        l.append(future)
    
    # 關閉進程池,等所有的進程執(zhí)行完畢
    p.shutdown(wait=True)
    for future in l:
        parse(future.result())
    print('完成時間:',time.time()-start)
    #完成時間: 13.209137678146362

<2>異步調用方式:只調用,不等返回值,可能存在耦合,但是速度快

def task(name):
    print("%s %s is running" %(name,os.getpid()))
    time.sleep(random.randint(1,3))
if __name__ == '__main__':
    p = ProcessPoolExecutor(4) # 設置進程池內進程
    for i in range(10):
        # 異步調用方式,只調用,不等返回值
        p.submit(task,'進程pid:') # 傳參方式(任務名,參數(shù)),參數(shù)使用位置參數(shù)或者關鍵字參數(shù)
    p.shutdown(wait=True)  # 關閉進程池的入口,等待池內任務運行結束
    print('主')
##################
##################
# 另一個異步調用的demo
def get(url):
    print('%s GET %s' % (os.getpid(),url))
    time.sleep(3)
    reponse = requests.get(url)
    if reponse.status_code == 200:
        res = reponse.text
    else:
        res = "下載失敗"
    parse(res)  # 沒有返回值
def parse(res):
    time.sleep(1)
    print('%s 解析結果為%s' %(os.getpid(),len(res)))

if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',

    ]
    p = ProcessPoolExecutor(9)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
    p.shutdown(wait=True)
    print("完成時間",time.time()-start)#  完成時間 6.293345212936401

<3>怎么使用異步調用方式,但同時避免耦合的問題?

(1)進程池:異步 + 回調函數(shù),,cpu密集型,同時執(zhí)行,每個進程有不同的解釋器和內存空間,互不干擾

def get(url):
    print('%s GET %s' % (os.getpid(), url))
    time.sleep(3)
    response = requests.get(url)
    if response.status_code == 200:
        res = response.text
    else:
        res = '下載失敗'
    return res
def parse(future):
    time.sleep(1)
    # 傳入的是個對象,獲取返回值 需要進行result操作
    res = future.result()
    print("res",)
    print('%s 解析結果為%s' % (os.getpid(), len(res)))
if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',
    ]
    p = ProcessPoolExecutor(9)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
        #模塊內的回調函數(shù)方法,parse會使用future對象的返回值,對象返回值是執(zhí)行任務的返回值
        #回調應該是相當于parse(future)
        future.add_done_callback(parse)
   p.shutdown(wait=True)
    print("完成時間",time.time()-start)#完成時間 33.79998469352722

(2)線程池:異步 + 回調函數(shù),IO密集型主要使用方式,線程池:執(zhí)行操作為誰有空誰執(zhí)行

def get(url):
    print("%s GET %s" %(current_thread().name,url))
    time.sleep(3)
    reponse = requests.get(url)
    if reponse.status_code == 200:
        res = reponse.text
    else:
        res = "下載失敗"
    return res
def parse(future):
    time.sleep(1)
    res = future.result()
    print("%s 解析結果為%s" %(current_thread().name,len(res)))
if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',
    ]
    p = ThreadPoolExecutor(4)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
        future.add_done_callback(parse)
    p.shutdown(wait=True)
    print("主",current_thread().name)
    print("完成時間",time.time()-start)#完成時間 32.52604126930237

3、總結

  • 1、線程不是越多越好,會涉及cpu上下文的切換(會把上一次的記錄保存)。
  • 2、進程比線程消耗資源,進程相當于一個工廠,工廠里有很多人,里面的人共同享受著福利資源,,一個進程里默認只有一個主線程,比如:開啟程序是進程,里面執(zhí)行的是線程,線程只是一個進程創(chuàng)建多個人同時去工作。
  • 3、線程里有GIL全局解鎖器:不允許cpu調度
  • 4、計算密度型適用于多進程
  • 5、線程:線程是計算機中工作的最小單元
  • 6、進程:默認有主線程 (幫工作)可以多線程共存
  • 7、協(xié)程:一個線程,一個進程做多個任務,使用進程中一個線程去做多個任務,微線程
  • 8、GIL全局解釋器鎖:保證同一時刻只有一個線程被cpu調度

到此這篇關于python中ThreadPoolExecutor線程池和ProcessPoolExecutor進程池的文章就介紹到這了,更多相關python ThreadPoolExecutor 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 上手簡單,功能強大的Python爬蟲框架——feapder

    上手簡單,功能強大的Python爬蟲框架——feapder

    這篇文章主要介紹了上手簡單,功能強大的Python爬蟲框架——feapder的使用教程,幫助大家更好的利用python進行爬蟲,感興趣的朋友可以了解下
    2021-04-04
  • 深入理解Python裝飾器

    深入理解Python裝飾器

    裝飾器(decorator)是一種高級Python語法。裝飾器可以對一個函數(shù)、方法或者類進行加工。這篇文章主要介紹了深入理解Python裝飾器的相關資料,需要的朋友可以參考下
    2016-07-07
  • Python拼接字符串的7種方法總結

    Python拼接字符串的7種方法總結

    這篇文章主要給大家總結介紹了關于Python拼接字符串的7種方法,分別是來自C語言的%方式、format()拼接方式、() 類似元組方式、面向對象模板拼接、join()拼接方式以及f-string方式,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2018-11-11
  • python實現(xiàn)輸出一個序列的所有子序列示例

    python實現(xiàn)輸出一個序列的所有子序列示例

    今天小編就為大家分享一篇python實現(xiàn)輸出一個序列的所有子序列示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • Django項目開發(fā)中cookies和session的常用操作分析

    Django項目開發(fā)中cookies和session的常用操作分析

    這篇文章主要介紹了Django項目開發(fā)中cookies和session的常用操作,結合實例形式分析了Django中cookie與session的檢查、設置、獲取等常用操作技巧,需要的朋友可以參考下
    2018-07-07
  • 簡單快捷:NumPy入門教程的環(huán)境設置

    簡單快捷:NumPy入門教程的環(huán)境設置

    NumPy是Python語言的一個擴展程序庫,支持高階大量的維度數(shù)組與矩陣運算,此外也針對數(shù)組運算提供大量的數(shù)學函數(shù)庫,本教程是為那些想了解NumPy的基礎知識和各種功能的人準備的,它對算法開發(fā)人員特別有用,需要的朋友可以參考下
    2023-10-10
  • python Flask實現(xiàn)restful api service

    python Flask實現(xiàn)restful api service

    本篇文章主要介紹了python Flask實現(xiàn)restful api service,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • 用Python編寫簡單的微博爬蟲

    用Python編寫簡單的微博爬蟲

    這篇文章主要介紹了如何利用Python編寫一個簡單的微博爬蟲,感興趣的小伙伴們可以參考一下
    2016-03-03
  • 在Python3.74+PyCharm2020.1 x64中安裝使用Kivy的詳細教程

    在Python3.74+PyCharm2020.1 x64中安裝使用Kivy的詳細教程

    這篇文章主要介紹了在Python3.74+PyCharm2020.1 x64中安裝使用Kivy的詳細教程,本文通過圖文實例相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • python3中類的繼承以及self和super的區(qū)別詳解

    python3中類的繼承以及self和super的區(qū)別詳解

    今天小編就為大家分享一篇python3中類的繼承以及self和super的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06

最新評論