English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Parallelism based on threads in Python

In computer science, a thread is a set of instructions that can be independently managed by a scheduler, which is part of the operating system.

The main function of threads is to run multiple threads at the same time. Thread means different tasks, function calls in the program, and multiple threads running simultaneously, which does not mean that they are executed on different computers.

Multithreading is used in both cases.

  • When the output of the subprogram needs to be combined with the main program.

  • When the main program contains code that is relatively independent of each other.

Thread module

Python provides a very powerful threading module and also provides advanced support for threads.

The threading module defines many functions that are used to obtain data related to threads, and these functions are executed automatically.

threading.active_count()

This function returns the number of currently active Thread objects. Here, the count returned is equal to the length of the list returnedenumerate().

threading.current_thread()

This function returns the current Thread object, which corresponds to the controlling thread of the caller.

threading.get_ident()

This function returns the 'thread identifier' of the current thread. It is a non-zero integer.

threading.enumerate()

This function returns a list of all currently active Thread objects (including daemon threads). The current_thread() function creates virtual threads and the main thread, and excludes terminated threads and threads that have not yet started.

threading.main_thread()

This function returns the main thread object.

threading.settrace(func)

After starting all threads from the thread module, set the trace function. Inrun()Before calling this function, it will pass to sys.settrace() for each thread.

threading.setprofile(func)

After starting all threads from the thread module, set the configuration file function. Inrun()Before calling this function, it will pass to sys.setprofile() for each thread.

threading.stack_size([size])

This function returns the size of the thread stack and is used when creating a new thread.

Thread.TIMEOUT_MAX

This is a constant that has the maximum value of the timeout parameter for blocking functions (Lock.acquire(), RLock.acquire(), Condition.wait(), etc.).

Example Code

import threading
def trace_function():
   print("Passing the trace function")
   def profile():
      print("PROFILE THREAD: " + str(threading.current_thread().getName()))
      class mythread(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("ACTIVE THREADS ARE: "+ str(threading.active_count()))
         print("CURRENT THREAD IS: " + str(threading.current_thread().getName()))
         my_thread1 mythread("PP", 500)
         my_thread2 mythread("PythonProgram", 1000);
         print("NAME OF THE MAIN THREAD: ") + str(threading.main_thread().getName()))
         print("IDENTIFICATION OF MAIN THREAD: ")+ str(threading.get_ident()))
         print("STACK SIZE = ") + str(threading.stack_size()))
      print(threading.settrace(trace_function()))
   threading.setprofile(profile())
my_thread1.start()
my_thread2.start()
print("LIST OF ENUMERATION: ")
print(threading.enumerate())
print("EXIT")

Output Result

NAME OF THE MAIN THREAD: MainThread
IDENTIFICATION OF MAIN THREAD: 5436
STACK SIZE = 0
Passing the trace function
None
PROFILE THREAD: MainThread
500
1000LIST OF ENUMERATION: ACTIVE THREADS ARE: 6
[<_MainThread(MainThread, started 5436))>, <Thread(Thread-4, started daemon 1960)>, <Heartbeat(Thread-5, started daemon 6452))>, <HistorySavingThread(IPythonHistorySavingThread, started 4304))>, <mythread(Thread-8, started 8460)>, <mythread(Thread-9, started 4668))]
EXIT
CURRENT THREAD IS: Thread-8
ACTIVE THREADS ARE: 5
CURRENT THREAD IS: Thread-9