Thread-Based Parallelism in Python

A multithreaded program consists of subroutines, each of which is processed separately by different threads. Multithreading allows parallelism in program execution. All active threads run concurrently, effectively sharing CPU resources and thus speeding up program execution. Multithreading is commonly used when:

  1. There are subroutines whose output must be concatenated by the main program.
  2. The main program contains sections of code that are relatively independent of each other.

A multithreaded program simultaneously performs different tasks within the same process, where different threads share the data space with each other as well as with the main thread.

Starting a new topic

The python threads module provides function calls that are used to create new threads. The __init__ function is used to initialize data associated with new threads, while the run function defines the behavior of the thread as soon as the thread starts executing it.

To create a new theme:

  1. Create a subclass of the thread class.
  2. Override the __init__ function of the thread class. This method initializes a thread-specific date.
  3. Override the run method to define thread behavior.

# Python program for demonstration
# initializing a new stream

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 ( " Python.Engineering " , 2000 ); 

 
thread1.start ()
thread2.start ()

 

print ( "Exit" )

Exit:

 GFG 1000 Python.Engineering 2000 Exit 

Threading module

The Threading module in Python provides powerful and high-level support for threads.

The Threading module defines the following function calls that are used to retrieve data associated with streams. All of these functions are performed atomically.

  1. active_count (): returns the number of Thread objects that are currently alive. The returned count is equal to the length of the list returned by enumerate (). 
    Syntax :
    threading.active_count()
  2. current_thread (): Returns the current Thread object corresponding to the caller`s thread of control. If the caller`s control flow was not created through the threads module, a dummy thread object with limited functionality is returned. 
    Syntax :
    threading.current_thread()
  3. get_ident (): returns the “thread id” of the current thread. This is a nonzero integer. Its meaning is not directly relevant; it is intended to be used as a magic cookie, for example to index a dictionary of stream-specific data. Stream IDs can be recycled when exiting a stream and creating another stream. 
    Syntax :
    threading.get_ident()
  4. enumerate (): returns a list of all Thread objects that are currently active. The list includes daemon 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()
  5. main_thread (): returns the main Thread object. Under normal conditions, the main thread is the thread from which the Python interpreter was started. 
    Syntax :
    threading.main_thread()
  6. settrace (func): set a trace function for all threads started from the threads module. The function is passed to sys.settrace () for each thread before calling the run () method. 
    Syntax :
    threading.settrace(func)
  7. setprofile (func): set profile function for all threads started from thread module. The function is passed to sys.setprofile () for each thread before calling the run () method. 
    Syntax :
    threading.setprofile(func)
  8. stack_size ([size]): returns the size of the thread`s stack used when creating new threads. 
    Syntax :
    threading.stack_size((size>)

This module also includes constant:

  • TIMEOUT_MAX: maximum allowed value for the timeout parameter of lock functions (Lock.acquire (), RLock.acquire (), Condition.wait (), etc.) . D.). Setting a timeout greater than this value will raise an OverflowError. 
    Syntax :
    threading.TIMEOUT_MAX

# Python program for demonstration
# streams 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" )

Exit :

 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 

Link:

This article courtesy of Mayank Kumar . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.