Skip to content Skip to sidebar Skip to footer

How To Give Different Names To Threadpoolexecutor Threads In Python

I have the below code for creating threads and running them. from concurrent.futures import ThreadPoolExecutor import threading def task(n): result = 0 i = 0 for i in

Solution 1:

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='')

Solution 2:

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 ThreadPoolExecutor
import threading
import time

deftask(n):
    result = 0
    i = 0for i inrange(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: 45 ThreadPoolExecutor-0_0 with variable 100: 4950

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

from concurrent.futures import ThreadPoolExecutor
import threading
import time

deftask(n):
    result = 0
    i = 0for i inrange(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: 45 ThreadPoolExecutor-0_1 with variable 100: 4950

Post a Comment for "How To Give Different Names To Threadpoolexecutor Threads In Python"