concurrent.future to execute two different functions with different parameters

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)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x