Introduction

One of Python's greatest strengths is its support for concurrency and multithreading, which allow us to run multiple tasks simultaneously and dramatically improve the performance of our programs. Threading is a powerful way to achieve this, enabling us to write more efficient and responsive applications by dividing our code into multiple threads that can run independently of each other. In this Python tutorial, we'll delve into the world of threading in Python, exploring its benefits and pitfalls, and learning how to use it to create more efficient and reliable software.

Table of Contents :

  • What are single-threaded applications
  • Multi-threaded program in python
  • Passing arguments to threads in python
  • Uses of Python threading
  • A Practical Python threading example

What are single-threaded applications :

  • In a single-threaded application, all tasks are performed in a sequence. 
  • The current task needs to complete before the next one can begin execution.
  • This can cause slow or inefficient processing when tasks are time-consuming.
  • Multithreading is a solution for such problems.

Multi-threaded program in python :

  • In Python, multithreading can be implemented using the  threading  module.
  • The following example creates two threads that execute concurrently:

import threading
import time

def worker(num):
   """Thread worker function"""
   time.sleep(1)
   print(f'Worker {num} executed')

threads = []
for i in range(5):
   t = threading.Thread(target=worker, args=(i,))
   threads.append(t)
   t.start()
   
   
   

Passing arguments to threads in python :

  • Arguments can be passed to a thread by passing them as a tuple in the  args  parameter while creating the thread.
  • The arguments can then be accessed in the thread function using unpacking.

def worker(num, name):
   """Thread worker function"""
   print(f'{name} executed worker {num}')


t = threading.Thread(target=worker, args=(1, 'Thread 1'))


Uses of Python threading :

  • Threading is useful when you want to execute multiple tasks simultaneously.
  • It is recommended to use threading if the tasks are I/O bound, such as file I/O or network I/O.
  • If the tasks are CPU bound or require heavy computation, multiprocessing is a better solution.

A Practical Python threading example :

  • Below is an example where three threads are created to process three different files concurrently:

import threading

def process_file(file_name):
   print(f"Processing {file_name}")
# Define file names for each thread
file_names = ['file1.txt', 'file2.txt', 'file3.txt']


# Create threads
threads = []
for file in file_names:
   t = threading.Thread(target=process_file, args=(file,))
   threads.append(t)
   t.start()

# Wait for threads to complete
for t in threads:
   t.join()
   
   
   
 

Prev. Tutorial : Processes and Threads

Next Tutorial : Multithreaded program