concurrent.future 用不同的参数执行两个不同的函数

concurrent.future to execute two different functions with different parameters

我正在尝试让 concurrent.future 执行两个具有不同参数的不同函数。但是,它没有成功。需要的功能如下:

def func1(para1, para2):
    time.sleep(para1)
    print(para2)
def func2(para1, para2, para3):
    time.speep(para2)
    print(para2+para3)

许多在线教程演示了多次使用同一函数,每个函数只有 1 个参数。我没有运气 运行 2 个具有不同参数的不同函数 运行 使用 concurrent.future。有什么想法吗?

根据 James 的回复修复了代码:

from concurrent.futures import ThreadPoolExecutor, wait
import time
start_time = time.time()

def fn_a(s,v):
    t_sleep = s
    print("function a: Wait {} seconds".format(t_sleep))
    time.sleep(t_sleep)
    ret = v * 5 # return different results
    print(f"function a: return {ret}")
    return ret

def fn_b(s,v):
    t_sleep = s
    print("function b: Wait {} seconds".format(t_sleep))
    time.sleep(t_sleep)
    ret = v * 10 # return different results
    print(f"function b: return {ret}")
    return ret

def fn_c(s,v):
    t_sleep = s
    print("function c: Wait {} seconds".format(t_sleep))
    time.sleep(t_sleep)
    ret = v * 20 # return different results
    print(f"function c: return {ret}")
    return ret

output = []

with ThreadPoolExecutor() as executor:
    futures = []
    futures.append(executor.submit(fn_a, 5, 1.1))
    futures.append(executor.submit(fn_b, 4, 2.2))
    futures.append(executor.submit(fn_c, 8, 3.3))
    complete_futures, incomplete_futures = wait(futures)
    for f in complete_futures:
        output.append(f.result())
        print(str(f.result()))

elapsed = (time.time() - start_time)
print(f"Total time of execution {round(elapsed, 4)} second(s)")
print("Output is:",output)

您可以使用您想要的参数将函数按顺序提交给您的执行器。

import time
from concurrent.futures import ThreadPoolExecutor

def func1(para1, para2):
    time.sleep(para1)
    print(para2)

def func2(para1, para2, para3):
    time.sleep(para1)
    print(para2+para3)

with ThreadPoolExecutor(2) as ex:
    futures = []
    futures.append(ex.submit(func1, 3, 'hello'))
    futures.append(ex.submit(func2, 2, 'world', 'blah'))

# prints:
worldblah
hello