How to give different names to ThreadPoolExecutor threads in Python How to give different names to ThreadPoolExecutor threads in Python multithreading multithreading

How to give different names to ThreadPoolExecutor threads in Python


from the docs:

New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.

using the thread_name_prefix argument:

concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')


You say: "both the threads have the same name".
That's not correct! The name is the same because the same thread is used for both tasks: in fact task() exits immediately.
In order to have both threads involved, you have to add some sleep in your task() function.

Just to recap:

(1) without sleep:

from concurrent.futures import ThreadPoolExecutorimport threadingimport timedef task(n):    result = 0    i = 0    for i in range(n): result = result + i    print(f'{threading.current_thread().name} with variable {n}: {result}')    executor = ThreadPoolExecutor(max_workers=3)executor.submit(task, (10))executor.submit(task, (100))    

In this case the output will be:

ThreadPoolExecutor-0_0 with variable 10: 45ThreadPoolExecutor-0_0 with variable 100: 4950

(2) with a sleep inside task(), to make the function longer in time:

from concurrent.futures import ThreadPoolExecutorimport threadingimport timedef task(n):    result = 0    i = 0    for i in range(n): result = result + i    time.sleep(.5)    print(f'{threading.current_thread().name} with variable {n}: {result}')executor = ThreadPoolExecutor(max_workers=3)executor.submit(task, (10))executor.submit(task, (100)) 

In this case the output will be:

ThreadPoolExecutor-0_0 with variable 10: 45ThreadPoolExecutor-0_1 with variable 100: 4950