python concurrent.futures模塊的使用測試
概述
concurrent.futures 是 3.2 中引入的新模塊,它為異步執(zhí)行可調(diào)用對象提供了高層接口。
可以使用 ThreadPoolExecutor 來進(jìn)行多線程編程,ProcessPoolExecutor 進(jìn)行多進(jìn)程編程,兩者實現(xiàn)了同樣的接口,這些接口由抽象類 Executor 定義。
這個模塊提供了兩大類型,一個是執(zhí)行器類 Executor,另一個是 Future 類。
執(zhí)行器用來管理工作池,future 用來管理工作計算出來的結(jié)果,通常不用直接操作 future 對象,因為有豐富的 API。
說明
Python3.2開始,標(biāo)準(zhǔn)庫為我們提供了concurrent.futures模塊,它提供了ThreadPoolExecutor和ProcessPoolExecutor兩個類,實現(xiàn)了對threading和multiprocessing的進(jìn)一步抽象,對編寫線程池/進(jìn)程池提供了直接的支持.
#! /usr/bin/env python # -*- coding: utf-8 -*-# # ------------------------------------------------------------------------------- # Name: demo3 # Author: yunhgu # Date: 2021/7/8 15:17 # Description: # ------------------------------------------------------------------------------- import os import time import threading from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed def work(x): time.sleep(1) temp = f"父進(jìn)程{os.getppid()}:子進(jìn)程{os.getpid()}:線程{threading.get_ident()}:{x}" return temp def sub_thread(): temp_list = [] with ThreadPoolExecutor(max_workers=3) as t: task_list = [t.submit(work, i) for i in range(5)] for task in as_completed(task_list): if task.done(): temp_list.append(task.result()) return temp_list def main(): print(f"主進(jìn)程:{os.getpid()}") path_list = [] with ProcessPoolExecutor(max_workers=3) as p: task_list = [p.submit(sub_thread) for i in range(5)] for task in as_completed(task_list): if task.done(): path_list.append(task.result()) for path in path_list: print(path) if __name__ == '__main__': main()
不論你在什么時候開始,重要的是開始之后就不要停止。不論你在什么時候結(jié)束,重要的是結(jié)束之后就不要悔恨。
到此這篇關(guān)于python concurrent.futures模塊的使用測試 的文章就介紹到這了,更多相關(guān)python concurrent使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Tornado服務(wù)器中綁定域名、虛擬主機(jī)的方法
這篇文章主要介紹了Tornado服務(wù)器中綁定域名、虛擬主機(jī)的方法,本人查看了Tornado才得的方法,特此分享,需要的朋友可以參考下2014-08-08基于Django OneToOneField和ForeignKey的區(qū)別詳解
這篇文章主要介紹了基于Django OneToOneField和ForeignKey的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python中Sorted()函數(shù)的key參數(shù)使用方法詳解
這篇文章主要介紹了關(guān)于Python中Sorted()函數(shù)的key參數(shù)使用方法 ,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-06-06Python利用socket實現(xiàn)多進(jìn)程的端口掃描器
作為開發(fā)人員經(jīng)常需要查看服務(wù)的端口開啟狀態(tài)判斷服務(wù)是否宕機(jī)。特別是部署的服務(wù)比較多的情況下,可能存在幾個甚至幾十個服務(wù)端口的占用。所以本文將利用socket實現(xiàn)多進(jìn)程的端口掃描器,需要的可以參考一下2022-12-12