I am trying to make concurrent.future to execute two different functions with different parameters. However, it was not successful. The desired functions are listed as follows:
def func1(para1, para2):
time.sleep(para1)
print(para2)
def func2(para1, para2, para3):
time.speep(para2)
print(para2+para3)
Lots of online tutorials demonstrate same function used multiple times with only 1 parameter per function. I got no luck to run 2 different functions with different parameters to run using concurrent.future. Any idea?
Fixed code according to James' reply:
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)
You can submit the functions in sequence to your executor with your desired parameters.
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