Python - Naming the Threads



The name of a thread is for identification purpose only, and has no role as far as the semantics is concerned. More than one threads may have same name. Thread name can be specified as one of the parameters in thread() constructor.

thread(name)

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

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

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, you have to do the following −

  • Define a new subclass of the Thread class.

  • Override the __init__(self [,args]) method to add additional arguments.

  • Then, override the run(self [,args]) method to implement what the thread should do when started.

Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run()method.

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,6):
         time.sleep(5)
         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")

It will produce the following 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
Thread name: Thread-1 Count: 4
Thread name: Thread-2 Count: 4
Thread name: Thread-1 Count: 5
Exiting Thread-1
Thread name: Thread-2 Count: 5
Exiting Thread-2
Exiting Main Thread
Advertisements