waiting for one function to finish before starting another python concurrent

Question:

I don’t know if this is possible but i have a tool that make use of the python package concurrent the code looks something like this:

import concurrent.futures
import time

def func1():
    #do something
def func2():
    #do something separate
def func3():
    time.sleep(10)
    #do something different
def func4():
    time.sleep(10)
    #do something different

with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.submit(func1)
    executor.submit(func2)
    executor.submit(func3)
    executor.submit(func4)

I want to wait for function 2 to finish before starting function 3 and 4 (whilst function 1 is always running), I’ve found it takes just under 10 seconds to complete function 2 so I sleep function 3 and 4 for 10 seconds (obviously this is not practical as if I move to any other computer it could take more or less time).

Is there any way to do so, I’ve seen something about the wait function in the concurrent package but I don’t know if this applies in this case

I don’t care about the outputs of the functions.

any help would be really appreciated.

Asked By: Christopher Rae

||

Answers:

This may defeat the purpose of concurrency (i.e. if you want func3 to immediately follow func2 you may just want to put those into a single thread rather than having one thread wait on the other), but:

with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.submit(func1)
    executor.submit(func2).result()
    executor.submit(func3)

forces you to wait for func2’s result before you submit func3.

Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.