Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 range(n):
        result = result + i
    print("I: {}".format(result))
    print(f'Thread : {threading.current_thread()} executed with variable {n}')

def main():
    executor = ThreadPoolExecutor(max_workers=3)
    task1 = executor.submit(task, (10))
    task2 = executor.submit(task, (100))

if __name__ == '__main__':
    main()

When i run the code in my windows 10 machine this is the output which gets generated:

I: 45
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 10
I: 4950
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 100

Process finished with exit code 0

As we see both the threads have the same name. How do i differentiate between them by giving them different names ? Is this somehow a feature of the concurrent.futures class ?

Many thanks for any answers.

like image 466
Subhayan Bhattacharya Avatar asked Jul 20 '18 09:07

Subhayan Bhattacharya


People also ask

How do you name a thread in Python?

setName() Method. Thread. setName() method is an inbuilt method of the Thread class of the threading module in Python. It uses a Thread object and sets the name of the thread.

Does Python ThreadPoolExecutor reuse threads?

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

Does ThreadPoolExecutor use multiple cores?

It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on many-core machines.

How does ThreadPoolExecutor work in Python?

ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously. An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.


1 Answers

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

like image 92
ospider Avatar answered Sep 27 '22 23:09

ospider