繁体   English   中英

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)

许多在线教程演示了多次使用相同的 function,每个 function 仅使用 1 个参数。我没有运气使用 concurrent.future 运行具有不同参数的 2 个不同函数。 任何的想法?

根据 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM