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:
Basic syntax of the Thread
class constructor is:
Thread(group=None, target=None, name=None, args=(), kwarg)
where,
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.
Here are some of the common functions and constructors that are available in the Thread class:
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
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…