Python - 如何通过执行顺序并行处理具有共享结果的独特函数?

Python - How to parallelise unique functions with shared results by order of execution?

每个函数(func1,等等)使 request 变成不同的 url:

def thread_map(ID):
    func_switch = \
        {
            0: func1,
            1: func2,
            2: func3,
            3: func4
        }

    with ThreadPoolExecutor(max_workers=len(func_switch)) as threads:
        futures = [threads.submit(func_switch[i], ID) for i in func_switch]
        results = [f.result() for f in as_completed(futures)]

        for df in results:
            if not df.empty and df['x'][0] != '':
                return df

        return pd.DataFrame()

for 循环(4 秒)相比,这要快得多(1.75 秒),但结果是无序的。

最好作为背景 processes/threads 返回以 func1 开头的相应数据帧。因此,如果不满足 func1 的条件,请检查 func2 等条件,因为结果已在后台获取。每个数据框都不同,但它们都包含相同的公共列 x.

非常感谢任何建议,而且我希望 ThreadPoolExecutor 适合这种情况。谢谢!

首先,让我们按照您的要求来做:

with ThreadPoolExecutor(max_workers=len(func_switch)) as threads:
    futures = [threads.submit(func_switch[i], ID) for i in func_switch]
results = [f.result() for f in futures]

这很简单。

要在完成时处理期货 将结果放在创建期货的列表中,您需要将每个期货与期货的顺序相关联创建:

futures = {} # this time a dictionary
creation_order = 0
with ThreadPoolExecutor(max_workers=len(func_switch)) as threads:
    for i in func_switch:
        future = threads.submit(func_switch[i], ID)
        futures[future] = creation_order # map the future to this value or any other values you want, such as the arguments being passed to the function, which happens to be the creation order
        creation_order += 1
results = [None] * creation_order # preallocate results
for f in as_completed(futures):
    result = f.result()
    index = futures[f] # recover original creation_order:
    results[index] = result

当然,如果您在等待所有期货完成后再对它们进行任何操作,那么使用 as_completed 方法就没有意义了。我只是想展示如果不是这种情况如何将完成的未来与原始创建顺序相关联的方法(或者更有用的是,在调用创建未来的辅助函数时使用的原始参数)。另一种方法是处理函数 return 传递的参数作为其结果的一部分。