Different way to create a thread in Python
Last Updated :
01 Oct, 2020
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System.
There are various ways to create a thread:
1) Create a Thread without using an Explicit function:
By importing the module and creating the Thread class object separately we can easily create a thread. It is a function-oriented way of creating a thread.
Python3
# Import required modules
from threading import *
# Explicit function
def display() :
for i in range(10) :
print("Child Thread")
# Driver Code
# Create object of thread class
Thread_obj = Thread(target=display)
# Executing child thread
Thread_obj.start()
# Executing main thread
for i in range(10):
print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above example, we have created an explicit function display() which prints Child Thread 10 times. Then we created a Thread class object named Thread_obj using the threading module. The first Thread is targeting the display() method i.e. display() method will be executed by this Thread object and the main thread(the second one) is targeting the for loop and will be responsible for executing by the Main Thread 10 times.
NOTE: Here which thread will get chance first (Main Thread or Child Thread) depends on the Thread Scheduler present in Python Virtual Machine (PVM), so we can't predict the output.
2) Create Thread by extending Thread Class :
In this method, we will extend the thread class from the threading module. This approach of creating a thread is also known as Object-Oriented Way.
Python3
# Import required module
from threading import *
# Extending Thread class
class Mythread(Thread):
# Target function for thread
def run(self):
for i in range(10):
print('Child Thread')
# Driver Code
# Creating thread class object
t = Mythread()
# Execution of target function
t.start()
# Executed by main thread
for i in range(10):
print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above example, we create a class that extends the Thread class, inside this class, we must override the run() method which will be the target function of our Child Thread, when the start() method is called it initiates the execution of the run() method(Target Function) of the thread.
3. Create Thread without extending Thread Class :
Another Object-Oriented Way of creating Thread is by not extending any thread class to create Thread.
Python3
# Import required modules
from threading import *
# Creating class
class Gfg:
# Creating instance method
def method1(self):
for i in range(10):
print('Child Thread')
# Driver Code
# Creating object of Gfg class
obj = Gfg()
# Creating object of thread by
# targeting instance method of Gfg class
thread_obj = Thread(target=obj.method1)
# Call the target function of threa
thread_obj.start()
# for loop executed by main thread
for i in range(10):
print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above program, we separately create an object of thread class and Gfg class, and whenever we create an object of thread class that time we have to mention the target function as well. The thread class object targets the instance method of the Gfg class. To start the execution of the target function we must call the start() method.
Similar Reads
Python | Different ways to kill a Thread
In general, killing threads abruptly is considered a bad programming practice. Killing a thread abruptly might leave a critical resource that must be closed properly, open. But you might want to kill a thread once some specific time period has passed or some interrupt has been generated. There are t
10 min read
How to create a new thread in Python
Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there
2 min read
Check if a Thread has started in Python
Problem: To know when will a launched thread actually starts running. A key feature of threads is that they execute independently and nondeterministically. This can present a tricky synchronization problem if other threads in the program need to know if a thread has reached a certain point in its ex
4 min read
Best way to learn python
Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time.
11 min read
Python time.thread_time_ns() Function
Python time.thread_time_ns() function is used to return the value of the sum of the system and user CPU time of the current thread. It is similar to time.thread_time() function. The difference is thread_time() function return the seconds of the CPU(Computer time) but  thread_time_ns() function retur
1 min read
Start and stop a thread in Python
The threading library can be used to execute any Python callable in its own thread. To do this, create a Thread instance and supply the callable that you wish to execute as a target as shown in the code given below - Code #1 : Python3 1== # Code to execute in an independent thread import time def co
4 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception hand
3 min read
Python time.thread_time() Function
Timer objects are used to represent actions that need to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action wa
2 min read
How to create telnet client with asyncio in Python
Telnet is a client/server application protocol that uses TCP/IP for connection. Telnet protocol enables a user to log onto and use a remote computer as though they were connected directly to it within the local network. The system that is being used by the user for the connection is the client and t
4 min read
Difference Between Multithreading vs Multiprocessing in Python
In this article, we will learn the what, why, and how of multithreading and multiprocessing in Python. Before we dive into the code, let us understand what these terms mean. A program is an executable file which consists of a set of instructions to perform some task and is usually stored on the disk
8 min read