python使用期物處理并發(fā)教程
learning from 《流暢的python》
1. futures.ThreadPoolExecutor
import os
import time
import sys
import requests
POP20_CC = ('CN IN US ID BR PK NG BD RU JP ' 'MX PH VN ET EG DE IR TR CD FR').split()
BASE_URL = 'http://flupy.org/data/flags'
DEST_DIR = './'
def save_flag(img, filename): # 保存圖像
path = os.path.join(DEST_DIR, filename)
with open(path, 'wb') as fp:
fp.write(img)
def get_flag(cc): # 獲取圖像
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
resp = requests.get(url)
return resp.content
def show(text): # 打印信息
print(text, end=' ')
sys.stdout.flush()
def download_many(cc_list):
for cc in sorted(cc_list):
image = get_flag(cc) # 獲取
show(cc) # 打印
save_flag(image, cc.lower() + '.gif') # 保存
return len(cc_list)
def main(download_many):
t0 = time.time()
count = download_many(POP20_CC)
elapsed = time.time() - t0
msg = '\n{} flags downloaded in {:.2f}s'
print(msg.format(count, elapsed)) # 計時信息
# ----使用 futures.ThreadPoolExecutor 類實現(xiàn)多線程下載
from concurrent import futures
MAX_WORKERS = 20 # 最多使用幾個線程
def download_one(cc):
image = get_flag(cc)
show(cc)
save_flag(image, cc.lower() + '.gif')
return cc
def download_many_1(cc_list):
workers = min(MAX_WORKERS, len(cc_list))
with futures.ThreadPoolExecutor(workers) as executor:
# 使用工作的線程數(shù)實例化 ThreadPoolExecutor 類;
# executor.__exit__ 方法會調(diào)用 executor.shutdown(wait=True) 方法,
# 它會在所有線程都執(zhí)行完畢 前阻塞線程
res = executor.map(download_one, sorted(cc_list))
# download_one 函數(shù) 會在多個線程中并發(fā)調(diào)用;
# map 方法返回一個生成器,因此可以迭代, 獲取各個函數(shù)返回的值
return len(list(res))
if __name__ == '__main__':
# main(download_many) # 24 秒
main(download_many_1) # 3 秒2. 期物
通常不應自己創(chuàng)建期物
只能由并發(fā)框架(concurrent.futures 或 asyncio)實例化 原因:期物 表示終將發(fā)生的事情,其 執(zhí)行的時間 已經(jīng)排定。因此,只有排定把某件事交給 concurrent.futures.Executor 子類處理時,才會創(chuàng)建 concurrent.futures.Future 實例
例如,Executor.submit() 方法的參數(shù)是一個可調(diào)用的對象,調(diào)用這個方法后會為傳入的可調(diào)用對象 排期,并返回一個期物
def download_many_2(cc_list):
cc_list = cc_list[:5]
with futures.ThreadPoolExecutor(max_workers=3) as executor:
to_do = []
for cc in sorted(cc_list):
future = executor.submit(download_one, cc)
# executor.submit 方法排定可調(diào)用對象的執(zhí)行時間,
# 然后返回一個 期物,表示這個待執(zhí)行的操作
to_do.append(future) # 存儲各個期物
msg = 'Scheduled for {}: {}'
print(msg.format(cc, future))
results = []
for future in futures.as_completed(to_do):
# as_completed 函數(shù)在期物運行結(jié)束后產(chǎn)出期物
res = future.result() # 獲取期物的結(jié)果
msg = '{} result: {!r}'
print(msg.format(future, res))
results.append(res)
return len(results)輸出: Scheduled for BR: <Future at 0x22da99d2d30 state=running> Scheduled for CN: <Future at 0x22da99e1040 state=running> Scheduled for ID: <Future at 0x22da99e1b20 state=running> Scheduled for IN: <Future at 0x22da99ec520 state=pending> Scheduled for US: <Future at 0x22da99ecd00 state=pending> CN <Future at 0x22da99e1040 state=finished returned str> result: 'CN' BR <Future at 0x22da99d2d30 state=finished returned str> result: 'BR' ID <Future at 0x22da99e1b20 state=finished returned str> result: 'ID' IN <Future at 0x22da99ec520 state=finished returned str> result: 'IN' US <Future at 0x22da99ecd00 state=finished returned str> result: 'US' 5 flags downloaded in 3.20s
3. 阻塞型I/O和GIL
CPython 解釋器本身就不是線程安全的,因此有全局解釋器鎖(GIL), 一次只允許使用一個線程執(zhí)行 Python 字節(jié)碼。因此,一個 Python 進程 通常不能同時使用多個 CPU 核心
標準庫中所有執(zhí)行阻塞型 I/O 操作的函數(shù),在等待操作系統(tǒng)返回結(jié)果時 都會釋放 GIL。 這意味著在 Python 語言這個層次上可以使用多線程,而 I/O 密集型 Python 程序能從中受益:一個 Python 線程等待網(wǎng)絡響應時,阻塞型 I/O 函數(shù)會釋放 GIL,再運行一個線程(網(wǎng)絡下載,文件讀寫都屬于 IO 密集型)
4. 使用concurrent.futures模塊啟動進程
這個模塊實現(xiàn)的是真正 的并行計算,因為它使用 ProcessPoolExecutor 類把工作分配給多個 Python 進程處理。 因此,如果需要做 CPU 密集型處理,使用這個模塊 能繞開 GIL,利用所有可用的 CPU 核心
使用 concurrent.futures 模塊能特別輕松地 把 基于線程 的方案轉(zhuǎn)成 基于進程 的方案
ProcessPoolExecutor 的價值體現(xiàn)在 CPU 密集型 作業(yè)上
以上就是python使用期物處理并發(fā)教程的詳細內(nèi)容,更多關(guān)于python期物處理并發(fā)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python實現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape)
今天小編就為大家分享一篇python實現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Django零基礎(chǔ)入門之運行Django版的hello world
這篇文章主要介紹了Django零基礎(chǔ)入門之運行Django版的hello world,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
Python內(nèi)置函數(shù)ord()的實現(xiàn)示例
ord()函數(shù)是用于返回字符的Unicode碼點,適用于處理文本和國際化應用,它只能處理單個字符,超過一字符或非字符串類型會引發(fā)TypeError,示例代碼展示了如何使用ord()進行字符轉(zhuǎn)換和比較2024-09-09
python3中類的繼承以及self和super的區(qū)別詳解
今天小編就為大家分享一篇python3中類的繼承以及self和super的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python中urllib與urllib2模塊的變化與使用詳解
urllib是python提供的一個用于操作URL的模塊,在python2.x中有URllib庫,也有Urllib2庫,在python3.x中Urllib2合并到了Urllib中,我們爬取網(wǎng)頁的時候需要經(jīng)常使用到這個庫,需要的朋友可以參考下2023-05-05
python的scipy.stats模塊中正態(tài)分布常用函數(shù)總結(jié)
在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于python的scipy.stats模塊中正態(tài)分布常用函數(shù)總結(jié)內(nèi)容,有興趣的朋友們可以學習參考下。2021-02-02
淺談pandas.cut與pandas.qcut的使用方法及區(qū)別
這篇文章主要介紹了淺談pandas.cut與pandas.qcut的使用方法及區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
使用python怎樣產(chǎn)生10個不同的隨機數(shù)
這篇文章主要介紹了使用python實現(xiàn)產(chǎn)生10個不同的隨機數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

