簡體   English   中英

如何在 Python 的 for 循環中引入多線程?

[英]How can I introduce multi-threading into a for loop in Python?

假設我有這樣一個帶有 for 循環的程序,我如何使用線程模塊使其成為多線程程序? 我試過了,但線程會重疊。 例如,如果我有 10 個線程,它將為單詞列表中的每個單詞發送 10 次 post 請求。

import aiohttp, asyncio

word_file = open("word.txt", "r")
word_list = word_file.readlines()
parsed_words = l = [i.strip() for i in word_list]

async def main():
    async with aiohttp.ClientSession() as session:
        for i in parsed_words:
            await session.post(f"https://redacted/{i}/")
            
asyncio.run(main())

假設您基本上希望並行運行請求而不顯式需要多線程:

您可以將其包裝成一個任務並將該任務放入隊列中,而不是直接等待發布請求。 在 main 函數的末尾添加一個 while 循環,該循環從隊列中取出任務並等待它們(大多數任務可能在那時已經完成)。 確保定義一個在隊列為空時中斷 while 循環的事件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM