我正在对一个涉及到 URL 的项目使用多重处理。我注意到,每当我使用 pool.imap_unordered() 时,无论我的迭代器是什么(假设它是一个包含数字 1 和 2 的列表,即 2 个数字),它都会运行该程序一次一个线程,然后因为列表中有2个数字,它会再运行一次。我似乎无法弄清楚这一点。我以为我明白一切应该做什么。 (不,无论我有多少个线程,它都不会运行得更快)(args.urls 最初是一个文件,然后我将文件中的所有内容转换为列表)一切正常,直到我添加了多重处理,所以我知道这不可能是我的非多处理相关代码中的错误。
from multiprocessing import Pool
import multiprocessing
import requests
arrange = [ lines.replace("\n", "") for lines in #file ]
def check():
for lines in arrange:
requests.get(lines)
def main():
pool = ThreadPool(4)
results = pool.imap_unordered(check, arrange)
最佳答案
所以我不完全确定你想要做什么,但也许这就是你需要的:
from multiprocessing import ThreadPool
import multiprocessing
import requests
arrange = [ line.replace("\n", "") for line in #file ]
def check(line):
requests.get(line) # remove the loop, since you are using multiprocessing this is not needed as you pass only one of the lines per thread.
def main():
pool = ThreadPool(4)
results = pool.imap_unordered(check, arrange) # This loops through arrange and provides the check function a single line per call
关于python - 多处理一次运行 1 个线程 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58126786/