Search code examples
pythonpython-3.xconcurrent.futures

python 3.7.3 - concurent.futures wait trouble


I'm a beginner in python multithreading more precisely ThreadPoolExecutor, and I'm here to ask you about it. I'm currently working with concurrent.futures module and I'm stuck with the waiting event. My programm go over the waiting event and finnish the execution without printing the final values of each funcitons returned. Can someone explain me why, pls ? :)

#!/usr/bin/env python
# module principal utilise concurent.futures pour executer 2 tacheds en parallele

from concurrent.futures import ThreadPoolExecutor
import shutil
import time
import threading



def function_AB():
    print("execution A_B")
    time.sleep(10)
    result_ab = "finish A_B"
    resultat_cd = Task_2.result(None)
    print(resultat_cd)
    return result_ab


def function_CD():
    print("execution C_D")
    time.sleep(3)
    result_cd = "finish C_D"
    resultat_ab = Task_1.result()
    print(resultat_ab)
    return result_cd


def main():
    executor = ThreadPoolExecutor(max_workers=2)
    #submit = ne ferme pas explictement le pool comparer au with ThreadPoolExecutor() /
    # appel non bloquant programme principal traite l'impression de la déclaration immédiatement et se bloque jusqu'à ce que tous les threads aient terminé 
    Task_1 = executor.submit(function_AB)
    Task_2 = executor.submit(function_CD)
    print(Task_1)
    print(Task_2)
    #permet de bloquer les threads jusqu'à la fin de leur exécution
    executor.shutdown(wait=True)



if __name__ == "__main__":
    start = time.time()
    main()
    print("Temps execution : {}".format(time.time() - start))



Solution

  • As written, task 1 is waiting on the result of the Future for task 2, while task 2 is waiting on the result of the Future for for task 1. This is a typical deadlock.

    Look at the documentation for Future.result() (emphasis mine):

    If timeout is not specified or None, there is no limit to the wait time.

    This means that both Future's will keep waiting for each other. This means that nothing will be printed and the process will never finish. :-)