Naming Threads in Python

Learn how to assign names to threads in Python for identification purposes using the threading.Thread constructor. Although thread names are used only for identification and do not affect functionality, they can help differentiate multiple threads. Explore the syntax for naming a thread in your Python programs.



The name of a thread is for identification purposes only and has no semantic role. Multiple threads can have the same name. The thread name can be specified as one of the parameters in the thread() constructor.

Syntax

Here is the syntax to name a thread:

Syntax

threading.Thread(name)

Here name is the thread name. By default, a unique name is constructed such as "Thread-N".

Example

Thread object also has a property object for getter and setter methods of the thread's name attribute.

Example

thread.name = "Thread-1"
The daemon Property

A Boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called.

Example

To implement a new thread using the threading module, follow these steps:

  1. Define a new subclass of the Thread class.
  2. Override the __init__(self [,args]) method to add additional arguments.
  3. Override the run(self [,args]) method to implement what the thread should do when started.

Once the new Thread subclass is created, create an instance and start a new thread by invoking start(), which in turn calls the run() method.

Example

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run(self):
        print("Starting " + self.name)
        for count in range(1, 4):
            time.sleep(2)
            print("Thread name: {} Count: {}".format(self.name, count))
        print("Exiting " + self.name)

# Create new threads
thread1 = MyThread("Thread-1")
thread2 = MyThread("Thread-2")

# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()

print("Exiting Main Thread")
Output

Starting Thread-1
Starting Thread-2
Thread name: Thread-1 Count: 1
Thread name: Thread-2 Count: 1
Thread name: Thread-1 Count: 2
Thread name: Thread-2 Count: 2
Thread name: Thread-1 Count: 3
Thread name: Thread-2 Count: 3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread