Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't concurrent.futures.ThreadPoolExecutor().submit return immediately?

In this code:

import concurrent.futures
import time

def pafter(t):
    time.sleep(t)
    print('Hi')

with concurrent.futures.ThreadPoolExecutor(5) as e:
    e.submit(pafter, 2)

print('With returned')

I expect to see:

With returned
Hi

but I see:

Hi
With returned

Why doesn't submit return immediately? What do I change to make it do so?

like image 766
Scott Deerwester Avatar asked Jul 24 '18 15:07

Scott Deerwester


People also ask

What is concurrent futures ThreadPoolExecutor?

The concurrent. futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor , or separate processes, using ProcessPoolExecutor .

How do you get results from ThreadPoolExecutor?

You can get results from the ThreadPoolExecutor in the order that tasks are completed by calling the as_completed() module function. The function takes a collection of Future objects and will return the same Future objects in the order that their associated tasks are completed.

How many employees does ThreadPoolExecutor have?

There is no maximum number of worker threads in the ThreadPoolExecutor. Nevertheless, your system will have an upper limit of the number of threads you can create based on how much main memory (RAM) you have available.

Does ThreadPoolExecutor reuse threads Python?

Heterogeneous tasks, not homogeneous tasks. Reuse threads, not single use. Manage multiple tasks, not single tasks.


1 Answers

Using the with statement is equivalent to calling executor.shutdown(), which is documented like this:

shutdown(wait=True)

Signal the executor that it should free any resources that it is using when the currently pending futures are done executing. Calls to Executor.submit() and Executor.map() made after shutdown will raise RuntimeError.

If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing.

You can avoid having to call this method explicitly if you use the with statement, which will shutdown the Executor (waiting as if Executor.shutdown() were called with wait set to True)

The bold sections explain the behavior you're seeing; the submit() call does return immediately, but the with statement will block until all submitted work is done. To change it, you need to not use the with statement, and instead explicitly call shutdown(wait=False).

like image 121
dano Avatar answered Sep 23 '22 18:09

dano