Thread-based parallelism in Python
Last Updated :
29 Jun, 2017
A multi-threaded program consists of sub-programs each of which is handled separately by different threads. Multi-threading allows for parallelism in program execution. All the active threads run concurrently, sharing the CPU resources effectively and thereby, making the program execution faster. Multi-threading is generally used when:
- There are sub-programs whose output needs to be combined by the main program.
- The main program contains sections of code that are relatively independent of each other.
A multi-threaded program handles different tasks at the same time, within the same process, where different threads share the data space with each other as well as the main thread.
Starting a new thread
The threading module in python provides function calls that is used to create new threads. The __init__ function is used for initializing the data associated with the new threads whereas, the run function defines the thread's behavior as soon as the thread starts it's execution.
In order to create a new thread, :
- Create a sub class of the thread class.
- Override the __init__ function of the thread class. This method will initialize the date specific to a thread.
- Override the run method to define the behavior of the thread.
Python
# Python program to demonstrate
# initializing a new thread
import threading
class thread(threading.Thread):
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
def run(self):
print(str(self.thread_name) +" "+ str(self.thread_ID));
thread1 = thread("GFG", 1000)
thread2 = thread("GeeksforGeeks", 2000);
thread1.start()
thread2.start()
print("Exit")
Output:
GFG 1000
GeeksforGeeks 2000
Exit
Threading module
Threading module in python provides powerful and high level support for threads.
Threading module defines the following function calls that is used to obtain thread related data. All these functions are executed atomically.
- active_count(): Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate().
Syntax:
threading.active_count()
- current_thread(): Return the current Thread object, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through the threading module, a dummy thread object with limited functionality is returned.
Syntax:
threading.current_thread()
- get_ident(): Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.
Syntax:
threading.get_ident()
- enumerate(): Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.
Syntax:
threading.enumerate()
- main_thread(): Return the main Thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started.
Syntax:
threading.main_thread()
- settrace(func): Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called.
Syntax:
threading.settrace(func)
- setprofile(func): Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called.
Syntax:
threading.setprofile(func)
- stack_size([size]): Return the thread stack size used when creating new threads.
Syntax:
threading.stack_size([size])
This module also includes the constant:
- TIMEOUT_MAX: The maximum value allowed for the timeout parameter of blocking functions (Lock.acquire(), RLock.acquire(), Condition.wait(), etc.). Specifying a timeout greater than this value will raise an OverflowError.
Syntax:
threading.TIMEOUT_MAX
Python
# Python program to demonstrate
# threading module
import threading
def trace_function():
print("Passing the trace function")
def profile():
print("Setting the profile of thread: " + str(threading.current_thread().getName()))
class thread(threading.Thread):
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
def run(self):
print(str(self.thread_ID));
print("Number of active threads: "+ str(threading.active_count()))
print("Name of current thread: " + str(threading.current_thread().getName()))
thread1 = thread("GFG", 1000)
thread2 = thread("GeeksforGeeks", 2000);
print("Name of main thread: " + str(threading.main_thread().getName()))
print("Identity of main thread: "+ str(threading.get_ident()))
print("Stack size = " + str(threading.stack_size()))
print(threading.settrace(trace_function()))
threading.setprofile(profile())
thread1.start()
thread2.start()
print("Enumeration list: ")
print(threading.enumerate())
print("Exit")
Output:
Name of main thread: MainThread
Identity of main thread: 139964150720320
Stack size = 0
Passing the trace function
None
Setting the profile of thread: MainThread
1000
Number of active threads: 2
Name of current thread: Thread-1
2000
Number of active threads: 2
Name of current thread: Thread-2
Enumeration list:
[]
Exit
Reference:
Similar Reads
Python Daemon Threads The threads that are always going to run in the background provide support to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background. This article is based o
6 min read
Parallel Processing in Python Parallel processing can increase the number of tasks done by your program which reduces the overall processing time. These help to handle large scale problems. In this section we will cover the following topics: Introduction to parallel processing Multi Processing Python library for parallel process
7 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
Asyncio Vs Threading In Python In Python, both Asyncio and Threading are used to achieve concurrent execution. However, they have different mechanisms and use cases. This article provides an in-depth comparison between Asyncio and Threading, explaining their concepts, key differences, and practical applications.Table of ContentKe
6 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
Run Tests in Parallel with PyTest Testing is one of the key factors of the application and code development. It is necessary whenever a team or an individual aims for a stable and performance-efficient product in a production environment. It also acts as a confidence booster for the developers as well as makes code modifications and
4 min read
Different way to create a thread in Python 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 creati
3 min read
Output of Python program | Set 16 (Threads) 1) What is the output of the following program? Python import threading barrier = threading.Barrier(4) class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print("Thre
3 min read
What is the Python Global Interpreter Lock (GIL) Python Global Interpreter Lock (GIL) is a type of process lock which is used by python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. This means that in python only one thread will be executed at a time. The performance of the
5 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