⚡ Multithreading
Last Updated: 08 Sept 2025
Multithreading means running multiple threads (mini tasks) at the same time inside a program.
- A thread is the smallest unit of a process.
- Useful when tasks are I/O bound (waiting for input/output like file read, API call).
✏ Creating a Thread
We use threading.Thread() to create a thread.
import threading
def print_numbers():
for i in range(5):
print(f"Number: {i}")
# Create thread
t1 = threading.Thread(target=print_numbers)
# Start thread
t1.start()
# Wait for thread to finish
t1.join()
print("Main program finished")
👉 Here:
- target=print_numbers → function executed by thread.
- start() → starts thread.
- join() → waits for thread to finish.
Create Multithreading Program with some arguments
import threading
import time
def task(name):
for i in range(3):
print(f"Task {name} - step {i}")
time.sleep(1)
# Create threads
t1 = threading.Thread(target=task, args=("A",),name="Thread A")
t2 = threading.Thread(target=task, args=("B",),name="Thread B")
# Start both
t1.start()
t2.start()
print("Is thread t1 alive?", t1.is_alive())
print("Is thread t2 alive?", t2.is_alive())
# Wait for both
t1.join()
t2.join()
print("After join t1, alive?", t1.is_alive())
print("After join t2, alive?", t2.is_alive())
print("All tasks done")
Note: Now we have two threads running in parallel.Output may be mixed.
🔒 Thread Synchronization (Lock)
When multiple threads access shared data, problems (race condition) can happen. We use threading.Lock() to prevent it.
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
for _ in range(100000):
with lock: # only one thread enters at a time
counter += 1
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
t1.start()
t2.start()
t1.join()
t2.join()
print("Final Counter:", counter)
Hinglish Tip 🗣"Lock ek darwaza hai – ek time par sirf ek thread andar aa sakta hai."
⚙ Daemon Threads
Daemon threads are threads that run in the background and are not affected by the main program.It automatically ends when the main program ends. Mainly use for background tasks.
import threading
import time
def background_task():
while True:
print("Running in background...")
time.sleep(1)
t = threading.Thread(target=background_task, daemon=True)
t.start()
time.sleep(3)
print("Main program exiting")