Multithreading & Multiprocessing in Python (threading Module)
Overview: A thread waiting for a file download can let another thread handle a second request.
Multithreading vs Multiprocessing in Python
- Thread: The smallest unit of execution within a process (also called a Lightweight Process).
- Process: An independent program in execution (a Heavyweight Process) with its own separate memory space.
- Definition: Running multiple threads concurrently within a single process
- Memory Space: All threads share the same memory and global variables
- Creation Speed: Fast and lightweight (low overhead)
- Crash Impact: If one thread crashes, it can affect the entire process
- Best Used For: I/O-Bound Tasks (File downloading, network requests, DB queries)
Single-Threaded vs Multithreaded Application
- Single-Threaded Application:
- Every Python program starts with one default thread called the Main Thread.
- Tasks execute strictly one after another (sequentially).
- Multithreaded Application:
- The Main Thread spawns multiple Child Threads (
t1,t2) that run concurrently (at the same time), drastically reducing total…
Creating Threads in Python (threading Module)
- Python provides the built-in
threadingmodule to create and manage threads. - Method 2: By Inheriting the
ThreadClass (Most Common in Exams!): You create a custom class that inherits fromthreading.Threadand override itsrun()method: - Method 3: Using a Callable Object (Class without Inheriting
Thread): You can create a normal class (or a class defining__call__()) and pass its method/instance toThread(target=...):
Life Cycle of a Thread in Python
- During its lifetime, a thread transitions through 5 distinct states:
- New (Born) State: A
Threadobject is created (t = Thread()), butstart()has not been called yet. - Runnable (Ready) State: Once
t.start()is called, the thread enters the ready queue waiting for the OS scheduler to allocate CPU time. - Running State: The CPU scheduler picks the thread and starts executing its
run()method. - Blocked / Waiting (Sleeping) State: The thread temporarily pauses execution because
time.sleep(),t.join(), orlock.acquire()was called. - Terminated (Dead) State: Once the
run()method finishes executing, the thread dies and cannot be restarted.
View diagram · Life Cycle of a Thread in Python
Can We Call run() Directly? Need for start() Method
- This is a very important DAVV BCA exam question:
- Question: *Can we call
t.run()directly instead oft.start()? - Answer: Yes , syntactically you can call
t.run()directly without getting an error, BUT it will NOT create a new separate thread! - If you call
t.run()directly, it behaves just like a normal function call executed by the Main Thread (Single-threaded… - Why we need
t.start(): Callingt.start()performs special Operating System magic: - It allocates a new call stack and registers a brand-new independent thread with the OS scheduler.
- It then automatically invokes the
run()method inside that new thread concurrently! - New Thread Created?: Yes, creates a new independent thread
Thread Methods (sleep, join), Synchronization (Lock) & Garbage Collection
Overview: Calling sleep merely delays the current thread.
Thread Control Methods: sleep() and join()
- A. The
sleep(seconds)Function (timeModule): Suspends (pauses) the execution of the currently running thread for a specified number of seconds. - While one thread is sleeping, the CPU switches to execute other active threads.
- B. The
join()Method (ThreadClass): When a thread callst1.join(), the calling thread (usually the Main Thread) **pauses and waits until threadt1finishes its…
Thread Synchronization & Race Condition
- What is a Race Condition?: When two or more threads try to modify the same shared resource (like a bank account balance or an available train seat) **at…
- What is Thread Synchronization?: Thread Synchronization is the mechanism that ensures only ONE thread can access a shared critical section at a time,…
- Synchronization Using the
LockClass (acquire()&release()): Python’sthreadingmodule provides theLockclass. lock = threading.Lock(): Creates a new Lock object (initially in the Unlocked state).lock.acquire(): A thread locks the resource before entering the critical section.lock.release(): Unlocks the resource after the critical task is done, allowing the next waiting thread to enter.
View diagram · How Thread Synchronization Works with Lock
Garbage Collection in Python
- In languages like C, programmers must manually allocate and free memory (
malloc()andfree()). - How Python’s Garbage Collector Works: Python uses two techniques together for automatic Garbage Collection:
- Reference Counting (Primary Mechanism):
- Every object in Python keeps a count of how many variables point to it.
- Whenever a variable is deleted (
del x) or reassigned (x = None), the object’s reference count decreases by1. - As soon as an object’s Reference Count reaches
0, Python immediately destroys the object and reclaims its memory! - Generational Garbage Collector (Cycle Detector):
- Handles Cyclic References (when two objects reference each other in a loop, so their count never hits
0).
Python Database Communication (PDBC)
Overview: A database cursor sends a statement using the driver’s parameter placeholders and bound values.
Database Drivers Used in PDBC
- To connect Python with a specific database, we import its corresponding driver module:
- SQLite (Serverless, File-based):**
sqlite3 - MySQL:
mysql.connector - PostgreSQL:
psycopg2 - Oracle:
cx_Oracle/oracledb
The 5 Standard Steps of PDBC (Exam Must-Know!)
- Whether you use SQLite or MySQL, every PDBC program follows the exact same 5 steps:
View diagram · 5 Steps of Python Database Communication (PDBC)
Important PDBC Methods Explained
connect(): Modulecon.cursor(): Connectioncur.execute(query): Cursorcur.executemany(q, list): Cursorcur.fetchone(): Cursorcur.fetchall(): Cursor
Complete PDBC Program 1: Using Built-in sqlite3
- This complete program creates a
college.dbdatabase, creates astudentstable, inserts records, and fetches them:
Complete PDBC Program 2: Connecting Python with MySQL
- When connecting to a MySQL Server in exams, use
mysql.connector:
Introduction to NumPy, Pandas & Matplotlib (Drawing Plots)
Overview: Use a NumPy array to calculate with many marks at once, a pandas table to group them by subject and Matplotlib to plot the resulting averages.
Introduction to NumPy (Numerical Python)
- NumPy (
import numpy as np) is the core library for scientific and numerical computing in Python. - Data Types: Heterogeneous (can mix types)
- Speed: Slower for math operations
- Memory Usage: Consumes more memory
- Element-wise Math:
[1, 2] * 2repeats list[1, 2, 1, 2]
Introduction to Pandas (Data Analysis Library)
- Pandas (
import pandas as pd) is built on top of NumPy and is used for cleaning, analyzing, and manipulating structured tabular data… - The Two Core Data Structures of Pandas:
Series(1-Dimensional): A single labeled column of data (like a 1D array with custom index labels). DataFrame(2-Dimensional): A 2D table consisting of Rows and Columns (just like an Excel sheet or SQL table).
Introduction to Matplotlib & Drawing Plots
- Matplotlib is Python’s most popular 2D Data Visualization library.
plt.plot(x, y): Line Graphplt.bar(x, y): Bar Chartplt.scatter(x, y): Scatter Plotplt.pie(sizes): Pie Chartplt.hist(data): Histogram