[Python] Python ThreadPoolExecutor: how to submit inside a function submitted

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I am using Python's concurrent.futures library with ThreadPoolExecutor and I want to submit inside a function submitted. The following code is a minimal example trying to submit f2 inside submitted f1:

    import concurrent.futures


    def f2():
    print("hello, f2")


    def f1():
    print("hello, f1")
    executor.submit(f2)


    with concurrent.futures.ThreadPoolExecutor(16) as executor:
    executor.submit(f1)


    Output (Python 3.12):

    hello, f1


    Output is the same even with:

    import concurrent.futures


    def f2():
    print("hello, f2")
    return 3


    def f1():
    print("hello, f1")
    print(executor.submit(f2).result())


    with concurrent.futures.ThreadPoolExecutor(16) as executor:
    executor.submit(f1)


    But this code works:

    import concurrent.futures


    def f2():
    print("hello, f2")
    return 3


    def f1():
    print("hello, f1")
    return executor.submit(f2).result()


    with concurrent.futures.ThreadPoolExecutor(16) as executor:
    print(executor.submit(f1).result())


    Output:

    hello, f1
    hello, f2
    3


    Why f2 is not called in example 1?

    Update:

    Without the with statement, the output of example 1 is random (i.e. sometimes outputs hello, f2 while sometimes not)


    The real use is:

    import concurrent.futures


    def f3():
    print("hello, f3")


    def f2():
    print("hello, f2")
    for i in range(10):
    executor.submit(f3)


    def f1():
    print("hello, f1")
    for i in range(10):
    executor.submit(f2)


    with concurrent.futures.ThreadPoolExecutor(16) as executor:
    for i in range(10):
    executor.submit(f1)


    So I want a simple solution.

    Continue reading...

Compartilhe esta Página