線程池map()方法傳遞多參數list
之前透過threading.thread()進行了助力介面的多執行緒並發,但是這個針對並發數量較少的時候比較好用,如果並發數量多,除了線程包協程這種處理方式的情況下,我們還可以採用線程池的方法。
線程池的實作通俗講就是把所有的任務放在了訊息佇列裡,開啟多個執行緒後執行線程,但執行緒執行結束後不會中斷執行緒任務,會從訊息佇列內繼續取得執行緒任務進行執行緒執行,這樣執行緒池就比多執行緒操作節省了許多創建執行緒與關閉執行緒的步驟,節約大部分資源與時間。
執行緒池並發需要引入模組
import concurrent.futures
ThreadPoolExecutor 內有兩種執行緒池方法map()與submit()今天先說map()方法
#他的語法為
with concurrent.futures.ThreadPoolExecutor() as pool: res = pool.map(craw, uid_list) print(res)
map()
內craw為方法名,這裡方法命不帶()uid_list
為方法參數,map()方法內需要傳遞list資料型別
#先看整體程式碼
##5000用戶並發助力def test_case_09(self): """5000用户并发助力""" # 通过yaml配置文件封装方法 获取uid_list uid_list = YamlHandler(YamlThePath().number_new).get_uid_list() # add_ticket获取5000账号登陆状态 with concurrent.futures.ThreadPoolExecutor() as pool: pool.map(AccountAccess().add_ticket, uid_list) # 5000账号线程池方法助力用户 with concurrent.futures.ThreadPoolExecutor() as pool: pool.map(PreheatMethod().help, [(uid, self.A, 1) for uid in uid_list]) # 获取用户被助力次数 response = PreheatMethod().init(self.A) print(f"当前用户被助力次数 :{response['data']['userInfo']['helpedCount']}次")再來看兩個介面的方法更好的感知一下首先是取得登陸狀態add_ticket
def add_ticket(self, uid): """ 获取单独用户t票 :param uid: 单独用户uid :return: """ self.data['url'] = ApiAddress().get_ticket self.data['host'] = ApiAddress().host self.params['uid'] = str(uid) self.params['type'] = 0 self.data['params'] = json.dumps(self.params) res = r().post(url=ApiAddress().ticket, data=self.data) print(f'获取t票结果:{uid}{res}') return uid很簡單的一個介面請求入參只有一個uid,但是注意一下這裡的uid不是list,他只是一個參數。 那麼有的同學就會有疑問,map()內傳遞的方法參數就是一個uid內容的list。 map()方法就是把你需要的參數存在list內,透過遍歷的方式去請求你指定的介面。 這時候可能有的人又會問,因為我當時也是這麼問自己的,如果一個方法內有多個參數,其中這些參數有的甚至都不是固定的內容怎麼辦。 咱們看一下另一個請求助力介面的方法
def help(self, agrs): """ 助力用户 :param agrs: uid:当前用户uid to_uid:助力用户uid count:助力次数 :return: """ uid, to_uid, count = agrs self.attrs['toUid'] = str(to_uid) self.attrs['count'] = count response = r().response(uid, self.code, "help", **self.attrs) logger.info(f'help response uid:{uid} to_uid:{to_uid}\n{response}') return response沒錯,我們透過元組的方式傳遞到助力介面內,透過元組內的關鍵字位置分別給指定的元素賦值。 再線程池的程式碼內,我們透過列表推導式把uid_list內的參數便利到你指定好的元組內,當然這裡如果是多個參數,也可以用字典,把字典便利key與value當作變化的參數,因為列表推導式給你回傳的是list,所以我們把需要的參數放在元組內,元組放在列表內,這樣就可以對多參數的方法使用map()線程池進行並發了。
with concurrent.futures.ThreadPoolExecutor() as pool: pool.map(PreheatMethod().help, [(uid, self.A, 1) for uid in uid_list])
[(uid, self.A, 1) for uid in uid_list]列表推導式取得後大概就是下方的list資料內容格式
以上是python之怎麼使用執行緒池map()方法傳遞多參數list的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

WebStorm Mac版
好用的JavaScript開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。