Understanding Threading in Python

Introduction to Concurrent Execution

Concurrent execution allows multiple tasks to run simultaneously, such as browsing the internet, playing music, and writing documents at the same time.

from time import sleep

def perform_singing():
    for i in range(3):
        print("Singing...%d" % i)
        sleep(1)

def perform_dancing():
    for i in range(3):
        print("Dancing...%d" % i)
        sleep(1)

if __name__ == "__main__":
    perform_singing()
    perform_dancing()

The output shows sequential execution:

Singing...0
Singing...1
Singing...2
Dancing...0
Dancing...1
Dancing...2

To achieve concurrent execution, we modify the code to use threads:

from time import sleep
import threading

def perform_singing():
    for i in range(3):
        print("Singing...%d" % i)
        sleep(1)

def perform_dancing():
    for i in range(3):
        print("Dancing...%d" % i)
        sleep(1)

if __name__ == "__main__":
    thread_one = threading.Thread(target=perform_singing)
    thread_two = threading.Thread(target=perform_dancing)
    thread_one.start()
    thread_two.start()

The result now reflects concurrent behavior:

Singing...0
Dancing...0
Dancing...1
Singing...1
Singing...2
Dancing...2

Definition of Concurrent Tasks

Concurrent Tasks

  1. A system capable of executing several tasks at once, such as listening to music and using word processors simultaneously. An operating system running multiple programs is considered a concurrent OS (e.g., Windows, Ubuntu, macOS, Android, iOS).
  2. A single program that handles multiple operations concurrently is referred to as a concurrent application.

Mechanism Behind Concurrent Execution

  1. A single-core CPU can execute one program at a time; however, achieving true parallelism requires multiple CPUs.
  2. On a single-core CPU, concurrent execution is simulated through rapid switching between tasks. For example, if a CPU has four cores, it can theoretically run four tasks concurrently, but in practice, many more programs can run due to the OS's scheduling mechanism. The OS rapidly swtiches between different tasks, giving each a small slice of time, wich creates the illusion of simultaneous execution.
  3. This is known as pseudo-concurrency. True concurrency occurs only with multi-core CPUs. When the number of tasks exceeds the core count, pseudo-concurrency is inevitable.

Concurrency vs Parallelism

  • Concurrency: Describes pseudo-concurrent execution.
  • Parallelism: Refers to actual concurrent execution.

Python offers two methods for concurrent execution: threads and processes.

Threads Overview

A thread represents an execution flow within a program.

Utilizing Threads for Concurrent Execution

  1. Every running program starts with one default thread called the main thread.
  2. Concurrent execution means creating additional threads to perform tasks alongside the main thread.
  3. In Python, the threading module simplifies thread creation compared to lower-level modules like thread.

Using the Threading Module

Sequential Execution Example

import time

def apologize():
    print("I'm sorry")
    time.sleep(1)

for i in range(5):
    apologize()

Output:

I'm sorry
I'm sorry
I'm sorry
I'm sorry
I'm sorry

Concurrent Execution with Threads

import threading
import time

def apologize():
    print("I'm sorry")
    time.sleep(1)

for i in range(5):
    thread_obj = threading.Thread(target=apologize)
    thread_obj.start()

Using threading module:

import threading
import time

def task_one():
    while True:
        print("Task One Running")
        time.sleep(1)

thread_obj = threading.Thread(target=task_one)
thread_obj.start()

while True:
    print("Main Task Running")
    time.sleep(1)

Sample Output:

Task One Running
Main Task Running
Task One Running
Main Task Running
...

Summary

  1. To run a separate task, create a new thread.
  2. In Python, use the Thread class from the threading module to create thread objects. These objects do not start automatically.
  3. Call the start() method on a thread object to initiate its execution. The target function passed during object creation determines what the thread will execute.
  4. To run multiple tasks concurrently, simply create multiple Thread instances.

Tags: python threading Concurrency multitasking

Posted on Fri, 08 May 2026 00:51:42 +0000 by railgun