Nearby lessons

136 of 159

Python Multi Threading - Introduction and Multi Tasking

📌 What You Will Learn
  • Define multi tasking and multi threading
  • Distinguish process based multi tasking from thread based multi tasking
  • Know the Python module that provides thread support
  • Identify the main thread in every Python program
  • Run a first program that prints the current executing thread

Python Multi Threading

Multi Threading is introduced under the topic Multi Tasking.

Before understanding Multi Threading, first we should understand what Multi Tasking means.

Multi Threading allows different independent parts of the same program to perform their work concurrently.

What is Multi Tasking?

Multi Tasking means executing several tasks simultaneously.

Simple Definition:

Executing several tasks simultaneously is called Multi Tasking.

For example, while working on a computer, we may perform several activities such as:

  • Writing a Python program
  • Listening to music
  • Downloading files

These activities can execute simultaneously.

Types of Multi Tasking

There are two types of Multi Tasking:

  1. Process Based Multi Tasking
  2. Thread Based Multi Tasking
                 Multi Tasking
                      │
          ┌───────────┴───────────┐
          │                       │
          ▼                       ▼
   Process Based             Thread Based
   Multi Tasking             Multi Tasking

Both approaches allow multiple tasks to make progress, but they differ in how those tasks are organized.

1. Process Based Multi Tasking

Process Based Multi Tasking means executing several tasks simultaneously where each task is a separate independent process.

Definition:

Executing several tasks simultaneously where each task is a separate independent process is called Process Based Multi Tasking.

Here, every task runs as an independent process.

Example of Process Based Multi Tasking

Consider the following example.

While typing a Python program in an editor, we can simultaneously:

  • Listen to MP3 songs
  • Download files from the Internet

Therefore, the computer may be performing:

Task 1 → Python Editor

Task 2 → MP3 Player

Task 3 → Internet Download

All these tasks execute simultaneously and independently.

Hence, this is an example of Process Based Multi Tasking.

Process Based Multi Tasking Diagram

                  Operating System
                         │
            ┌────────────┼────────────┐
            │            │            │
            ▼            ▼            ▼
      Python Editor   MP3 Player   Internet Download
            │            │            │
            ▼            ▼            ▼
        Process 1     Process 2     Process 3

All are separate independent processes.

Best Suitable For Process Based Multi Tasking

Process Based Multi Tasking is best suitable at the Operating System level.

An Operating System can execute and manage several independent applications or processes.

Examples include:

  • Python Editor
  • Music Player
  • Browser
  • File Downloader

Each application can run as a separate process.

2. Thread Based Multi Tasking

Thread Based Multi Tasking means executing several tasks simultaneously where each task is a separate independent part of the same program.

Each independent part is called a Thread.

Definition:

Executing several tasks simultaneously where each task is a separate independent part of the same program is called Thread Based Multi Tasking, and each independent part is called a Thread.

Understanding a Thread

A Thread represents an independent path of execution inside a program.

A single program can contain multiple threads.

Program
   │
   ├──── Thread 1
   │
   ├──── Thread 2
   │
   └──── Thread 3

All these threads belong to the same program.

Thread Based Multi Tasking Diagram

                     Program
                        │
             ┌──────────┼──────────┐
             │          │          │
             ▼          ▼          ▼
          Thread 1   Thread 2   Thread 3
             │          │          │
             └──────────┴──────────┘
                        │
                        ▼
               Same Python Program

All threads belong to the same program.

Best Suitable For Thread Based Multi Tasking

Thread Based Multi Tasking is best suitable at the Programmatic level.

It is useful when one program contains several independent jobs that can make progress concurrently.

One Program
     │
     ├── Job 1 → Thread 1
     ├── Job 2 → Thread 2
     └── Job 3 → Thread 3

Process Based vs Thread Based Multi Tasking

Feature Process Based Multi Tasking Thread Based Multi Tasking
Task Separate independent process Separate independent part of the same program
Execution Unit Process Thread
Program Relationship Tasks can belong to different programs Threads belong to the same program
Best Suitable For Operating System level Programmatic level
Example Editor + MP3 Player + Download Multiple independent jobs inside one program

Advantage of Multi Tasking

Whether it is:

  • Process Based Multi Tasking
  • Thread Based Multi Tasking

the main advantage of Multi Tasking is to improve the performance of the system by reducing response time.

Multiple Independent Tasks
          │
          ▼
Execute Concurrently
          │
          ▼
Better Resource Utilization
          │
          ▼
Reduced Response Time

Applications of Multi Threading

The main application areas of Multi Threading are:

  1. To implement Multimedia Graphics
  2. To develop Animations
  3. To develop Video Games
  4. To develop Web and Application Servers
  5. etc.

These types of applications can contain multiple independent jobs that need to make progress concurrently.

Important Note About Multi Threading

Wherever a group of independent jobs is available, it is highly recommended to execute them simultaneously instead of executing them one by one when concurrent execution is appropriate.

For such cases, we can go for Multi Threading.

Independent Jobs
      │
      ├── Job 1
      ├── Job 2
      └── Job 3
      │
      ▼
Execute Using Multiple Threads
      │
      ▼
Concurrent Execution

Python threading Module

Python provides an inbuilt module called:

threading

This module provides support for developing and managing threads.

Hence, developing multithreaded programs is convenient in Python.

To use the module, we can import it:

import threading

What is the Main Thread?

Every Python program by default contains one thread.

This default thread is called:

MainThread

Simple Definition:

The default thread that starts the execution of a Python program is called the Main Thread.

Even if we do not explicitly create any additional thread, the Python program already executes using the Main Thread.

Python Program Starts
        │
        ▼
   MainThread
        │
        ▼
Execute Program Statements

Program - Print the Name of the Current Executing Thread

🐍Code Cell
1import threading
2 
3print("Current Executing Thread:",
4 threading.current_thread().name)
Output
No output captured.

Output

Program Explanation

Step 1: Import the threading Module

import threading

The threading module provides support for creating and managing threads.


Step 2: Get the Current Executing Thread

threading.current_thread()

current_thread() returns the currently executing Thread object.

In this program, we have not created any child thread.

Therefore, the current executing thread is the default Main Thread.


Step 3: Get the Thread Name

.name

The name property of a Thread object returns the name of that thread.

The default thread name is:

MainThread

Step 4: Display the Thread Name

print("Current Executing Thread:",
      threading.current_thread().name)

Therefore, the output is:

Current Executing Thread: MainThread

Since every Python program starts with one default thread, its name is MainThread.

Understanding current_thread()

The current_thread() function returns the Thread object representing the thread that is currently executing the statement.

Syntax:

threading.current_thread()

In our example:

threading.current_thread()

returns the object representing:

MainThread

Understanding name property

The name property returns the name assigned to a Thread object.

Syntax:

thread_object.name

Example:

threading.current_thread().name

Result:

MainThread

Therefore:

current_thread()
      │
      ▼
Current Thread Object
      │
      ▼
name property
      │
      ▼
"MainThread"

Execution Flow

Start Python Program
        │
        ▼
Python Starts Default Thread
        │
        ▼
    MainThread
        │
        ▼
Import threading Module
        │
        ▼
Call current_thread()
        │
        ▼
Returns Current Thread Object
        │
        ▼
Read the name property
        │
        ▼
Returns "MainThread"
        │
        ▼
Display Output
        │
        ▼
Current Executing Thread:
MainThread

Process and Thread Concept

Process Based Multi Tasking

Operating System
      │
      ├── Process 1
      ├── Process 2
      └── Process 3


Thread Based Multi Tasking

Single Program
      │
      ├── Thread 1
      ├── Thread 2
      └── Thread 3

The major conceptual difference is that process-based tasks are separate processes, whereas thread-based tasks are independent execution paths inside the same program.

Complete Summary

Topic Description
Multi Tasking Executing several tasks simultaneously.
Types of Multi Tasking Process Based and Thread Based.
Process Based Multi Tasking Each task is a separate independent process.
Best Suitable Level for Process Based Operating System level.
Thread Based Multi Tasking Each task is a separate independent part of the same program.
Thread An independent part or execution path of the same program.
Best Suitable Level for Thread Based Programmatic level.
Main Advantage Improves performance by reducing response time.
Multi Threading Applications Multimedia Graphics, Animations, Video Games, Web Servers and Application Servers.
Python Module threading
Default Thread MainThread
current_thread() Returns the currently executing Thread object.
name property Returns the name of the Thread object.

Important Notes

  1. Executing several tasks simultaneously is called Multi Tasking.
  2. There are two types of Multi Tasking:
    • Process Based Multi Tasking
    • Thread Based Multi Tasking
  3. In Process Based Multi Tasking, each task is a separate independent process.
  4. Process Based Multi Tasking is best suitable at the Operating System level.
  5. Typing a Python program while listening to MP3 songs and downloading files is an example of Process Based Multi Tasking.
  6. In Thread Based Multi Tasking, each task is a separate independent part of the same program.
  7. Each independent execution part is called a Thread.
  8. Thread Based Multi Tasking is best suitable at the Programmatic level.
  9. The main advantage of Multi Tasking is to improve system performance by reducing response time.
  10. Multi Threading is commonly used for Multimedia Graphics, Animations, Video Games, Web Servers and Application Servers.
  11. When a group of independent jobs is available and concurrent execution is appropriate, Multi Threading can be used instead of executing every job one by one.
  12. Python provides the built-in threading module for thread-related programming.
  13. Every Python program starts with one default thread.
  14. The default thread is called MainThread.
  15. current_thread() returns the currently executing Thread object.
  16. name property returns the name of a thread.
📝 Key Takeaways
  • Multi tasking means executing several tasks simultaneously
  • Multi threading lets independent parts of the same program run concurrently
  • The threading module provides thread support in Python
  • Every Python program has a default Main Thread
  • current_thread().name identifies the running thread

🧠 Test Your Knowledge

13 Questions
Progress: 0 / 13