Python 线程池 ThreadPoolExecutor(二) - Python零基础入门教程
目錄
- 一.Python 線程池前言
- 二.Python 線程池 ThreadPoolExecutor 常用函數(shù)
- 1.線程池 as_completed 函數(shù)使用
- 2.線程池 map 函數(shù)使用
- 3.線程池 wait 函數(shù)使用
- 三.猜你喜歡
零基礎(chǔ) Python 學(xué)習(xí)路線推薦 : Python 學(xué)習(xí)目錄 >> Python 基礎(chǔ)入門(mén)
一.Python 線程池前言
緊接著上一篇文章 Python 線程池 ThreadPoolExecutor(一) 我們繼續(xù)對(duì)線程池深入一點(diǎn)了解,其實(shí) Python 中關(guān)于線程池,一共有兩個(gè)模塊:
- 1.threadpool — 是一個(gè)比較老的模塊了,現(xiàn)在雖然還有一些人在用,但已經(jīng)不再是主流了;
- 2.concurrent.futures — 目前線程池主要使用這個(gè)模塊,主流模塊;
二.Python 線程池 ThreadPoolExecutor 常用函數(shù)
除了 Python 線程池 ThreadPoolExecutor(一) 文章中介紹的 submit / cancel / done / result 函數(shù)外,今天還需要額外講解一下另外幾個(gè)函數(shù):
1.線程池 as_completed 函數(shù)使用
雖然 done 函數(shù)提供了判斷任務(wù)是否結(jié)束的方法,但是并不是太實(shí)用,因?yàn)槲覀儾⒉恢谰€程到底什么時(shí)候結(jié)束,需要一直判斷每個(gè)任務(wù)有沒(méi)有結(jié)束。這時(shí)就可以使用 as_completed 方法一次取出所有任務(wù)的結(jié)果。
as_completed 方法是一個(gè)生成器,在沒(méi)有任務(wù)完成的時(shí)候,會(huì)阻塞,在有某個(gè)任務(wù)完成的時(shí)候,就能繼續(xù)執(zhí)行 for 循環(huán)后面的語(yǔ)句,然后繼續(xù)阻塞住,循環(huán)到所有的任務(wù)結(jié)束。
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿說(shuō)編程 @Blog(個(gè)人博客地址): www.codersrc.com @File:Python 線程池 ThreadPoolExecutor.py @Time:2021/05/05 07:37 @Motto:不積跬步無(wú)以至千里,不積小流無(wú)以成江海,程序人生的精彩需要堅(jiān)持不懈地積累!"""from concurrent.futures import ThreadPoolExecutor, as_completed import time# 參數(shù)times用來(lái)模擬網(wǎng)絡(luò)請(qǐng)求的時(shí)間 def download_video(index):time.sleep(2)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2) urls = [1, 2, 3, 4, 5] all_task = [executor.submit(download_video, (url)) for url in urls]for task in as_completed(all_task):data = task.result()print("任務(wù){(diào)} down load success".format(data))''' 輸出結(jié)果:download video 1 finished at 2021-05-05 07:10:00 任務(wù)1 down load success download video 2 finished at 2021-05-05 07:10:00 任務(wù)2 down load success download video 3 finished at 2021-05-05 07:10:02 任務(wù)3 down load success download video 4 finished at 2021-05-05 07:10:02 任務(wù)4 down load success download video 5 finished at 2021-05-05 07:10:04 任務(wù)5 down load success '''代碼分析:
5 個(gè)任務(wù),2 個(gè)線程,由于在線程池構(gòu)造的時(shí)候允許同時(shí)最多執(zhí)行 2 個(gè)線程,所以同時(shí)執(zhí)行任務(wù) 1 和任務(wù) 2 ,重代碼的輸出結(jié)果來(lái)看,任務(wù) 1 和任務(wù) 2 執(zhí)行后,for 循環(huán)進(jìn)入阻塞狀態(tài),直到任務(wù) 1 或者任務(wù) 2 結(jié)束之后才會(huì) for 才會(huì)繼續(xù)執(zhí)行任務(wù) 3 / 任務(wù) 4 ,并保證同時(shí)執(zhí)行的最多只有兩個(gè)任務(wù)(關(guān)于自定義時(shí)間格式請(qǐng)參考:Python time 模塊).
2.線程池 map 函數(shù)使用
和 as_completed 方法不同的是:map 方法能保證任務(wù)的順序性,舉個(gè)例子:如果同時(shí)下載 5 個(gè)視頻,就算第二個(gè)視頻比第一個(gè)視頻先下載完成,也會(huì)阻塞等待第一個(gè)視頻下載完成并通知主線程之后,第二個(gè)下載完成的視頻才回通知主線程,保證按照順序完成任務(wù),下面舉個(gè)例子說(shuō)明一下:
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿說(shuō)編程 @Blog(個(gè)人博客地址): www.codersrc.com @File:Python 線程池 ThreadPoolExecutor.py @Time:2021/05/05 07:37 @Motto:不積跬步無(wú)以至千里,不積小流無(wú)以成江海,程序人生的精彩需要堅(jiān)持不懈地積累!"""from concurrent.futures import ThreadPoolExecutor, as_completed import time# 參數(shù)times用來(lái)模擬網(wǎng)絡(luò)請(qǐng)求的時(shí)間 def download_video(index):time.sleep(index)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2) urls = [3, 2, 1, 4, 5]for data in executor.map(download_video,urls):print("任務(wù){(diào)} down load success".format(data))''' 輸出結(jié)果:download video 2 finished at 2021-05-05 07:10:55 download video 3 finished at 2021-05-05 07:10:56 任務(wù)3 down load success 任務(wù)2 down load success download video 1 finished at 2021-05-05 07:10:56 任務(wù)1 down load success download video 4 finished at 2021-05-05 07:10:00 任務(wù)4 down load success download video 5 finished at 2021-05-05 07:10:01 任務(wù)5 down load success '''代碼分析:
重上面的輸出結(jié)果看來(lái),即便任務(wù) 2 比任務(wù) 3 先完成,for 循環(huán)輸出的內(nèi)容依舊是提示先完成的任務(wù) 3 再完成任務(wù) 2 ,根據(jù)列表 urls 順序輸出,保證任務(wù)的順序性!
3.線程池 wait 函數(shù)使用
**wait 方法有點(diǎn)類(lèi)似線程的 join 方法,能阻塞主線程,直到線程池中的所有的線程都操作完成!**實(shí)例代碼如下:
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿說(shuō)編程 @Blog(個(gè)人博客地址): www.codersrc.com @File:Python 線程池 ThreadPoolExecutor.py @Time:2021/05/05 07:37 @Motto:不積跬步無(wú)以至千里,不積小流無(wú)以成江海,程序人生的精彩需要堅(jiān)持不懈地積累!"""from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETED import time# 參數(shù)times用來(lái)模擬網(wǎng)絡(luò)請(qǐng)求的時(shí)間 def download_video(index):time.sleep(2)print("download video {} finished at {}".format(index,time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())))return indexexecutor = ThreadPoolExecutor(max_workers=2) urls = [1, 2, 3, 4, 5] all_task = [executor.submit(download_video,(url)) for url in urls]wait(all_task,return_when=ALL_COMPLETED)print("main ")''' 輸出結(jié)果:download video 2 finished at 2021-05-05 07:10:22 download video 1 finished at 2021-05-05 07:10:22 download video 3 finished at 2021-05-05 07:10:24 download video 4 finished at 2021-05-05 07:10:24 download video 5 finished at 2021-05-05 07:10:26 main '''** wait 方法接收 3 個(gè)參數(shù),等待的任務(wù)序列、超時(shí)時(shí)間以及等待條件。等待條件 return_when 默認(rèn)為 ALL_COMPLETED ,表明要等待所有的任務(wù)都結(jié)束。可以看到運(yùn)行結(jié)果中,確實(shí)是所有任務(wù)都完成了,主線程才打印出 main 。等待條件還可以設(shè)置為 FIRST_COMPLETED ,表示第一個(gè)任務(wù)完成就停止等待。**
三.猜你喜歡
未經(jīng)允許不得轉(zhuǎn)載:猿說(shuō)編程 ? Python 線程池 ThreadPoolExecutor(二)
總結(jié)
以上是生活随笔為你收集整理的Python 线程池 ThreadPoolExecutor(二) - Python零基础入门教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python eval 与 exec 函
- 下一篇: C语言 va_start / va_en