python - 多处理一次运行 1 个线程 x 次

标签 python parallel-processing multiprocessing

我正在对一个涉及到 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/

相关文章:

exception - F# MailboxProcessor - 邮箱的多个等待读者延续

Python 3.4 多重处理,代码不会超过循环(包含队列)

Python 多处理使用 pool.map 和列表

Python 多处理 IOError : [Errno 232] The pipe is being closed

python - 在 Python 中按长度拆分列表的列表

Python:如何更改电子邮件发件人的姓名?

python - 尝试使用带有通用参数的 mockito python stub 函数时出错

python - Gradle Exec 任务和流程输出

c# - asp.net 异步执行任务并更新 UI

foreach - PowerShell 的 `ForEach -Parallel` 的简写