Thread class and its Object

  • December 31, 2022
  • python
JOIN Clause

The Thread class in Python’s threading module is used to create and manage threads. We can extend this class to create a Thread or create a Thread class object directly and pass a member function from another class.

There are two methods for creating the Thread object and specifying the activity to be carried out:

  • by passing a callable object to the constructor
  • or, by overriding the run() method in a subclass.

Basic syntax of the Thread class constructor is:

Thread(group=None, target=None, name=None, args=(), kwarg)

where,

  • group: should be none. It is reserved for future extension.
  • target: The callable object or task that will be invoked by the run() method. We have specified the function names thread1 and thread2 as the value for this argument, as shown in the code example at the top. None is the default value.
  • name: This is used to specify the name of the thread. Thread-N, where N is a small decimal number, is used by default to generate a unique name.
  • args: This is the target invocation argument tuple. We can include values that can be used in the tragedy method. It has no default value, i.e. ()
  • kwargs: This is the target invocation’s keyword argument dictionary. This is the default.

Here’s an example of how to create and start a new thread in Python:

import threading

class MyThread(threading.Thread):
    def run(self):
        # code to be executed in the new thread

# create and start the thread
t = MyThread()
t.start()

The Thread class provides several methods for controlling and manipulating threads, such as start(), join(), and is_alive().

The Thread class has a run() method that is invoked whenever we start the thread by calling start() function. Also, run() function in the Thread class calls the callable entity (e.g. function) passed in target argument to execute that function in thread. But in our derived class we can override the run() function to our custom implementation like this.

Example: create a thread by passing a function to the Thread constructor

import threading

def my_function():
    # code to be executed in the new thread

# create and start the thread
t = threading.Thread(target=my_function)
t.start()

It’s important to note that a Thread object represents a thread of execution, not the actual thread itself. The thread of execution is created and managed by the Python interpreter.

Functions in the Thread class:

Here are some of the common functions and constructors that are available in the Thread class:

  • start(): starts the thread.
  • join([timeout]): waits for the thread to complete execution. The optional timeout argument specifies the maximum amount of time to wait, in seconds.
  • is_alive(): return True if the thread is still running, and False otherwise.
  • getName(): returns the name of the thread.

Example:

from threading import Thread
import time
# A class that extends the Thread class
class FileLoaderThread(Thread):
   def __init__(self, fileName, encryptionType):
       # Call the Thread class's init function
       Thread.__init__(self)
       self.fileName = fileName
       self.encryptionType = encryptionType
   # Override the run(0 function of Thread class
   def run(self):
       print('Started loading contents from file : ', self.fileName)
       print('Encryption Type : ', self.encryptionType)
       for i in range(5):
           print('Loading ... ')
           time.sleep(1)
       print('Finished loading contents from file : ', self.fileName)
def main():
   # Create an object of Thread
   th = FileLoaderThread('users.csv','ABC')
   # start the thread
   th.start()
   # print some logs in main thread
   for i in range(5):
       print('Hi from Main Function')
       time.sleep(1)
   # wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()

Output:

Started loading contents from file : users.csv
Encryption Type :  ABC
Hi from Main Function 
Loading ... 
Loading ... 
Hi from Main Function
Loading ... 
Hi from Main Function
Loading ... 
Hi from Main Function
Hi from Main Function
Loading ... 
Finished loading contents from file :  users.csv

This code defines a FileLoaderThread class that extends the Thread class from the threading module in Python. The FileLoaderThread class has a constructor that takes two arguments: fileName and encryptionType. These values are stored in the fileName and encryptionType attributes of the FileLoaderThread object.

When you run this code, it will create a new thread using the FileLoaderThread class and start it. The thread will print some messages and sleep for 1 second in a loop for a total of 5 iterations. Meanwhile, the main thread will print some messages and sleep for 1 second in a loop for a total of 5 iterations. Finally, the main thread will wait for the thread to finish before exiting.

Note: also read about Multithreading In Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *