Definition
A technique for executing multiple parts of a program concurrently by creating separate threads of execution.
Why It Matters
Python’s Global Interpreter Lock (GIL) makes multithreading tricky. If you use threads for CPU-bound tasks in Python, your program might actually run slower. Understanding when to use threads versus processes is essential for building responsive, high-performance applications.
Core Concepts
- The “Concurrency” Model: Threads allow a program to perform tasks “at the same time” (e.g., downloading a file in the background while the UI remains responsive).
threading.Thread: Create a thread withtarget=function_nameandargs=[arg1, arg2].start()vs.join():.start(): Begins execution of the thread..join(): Blocks the main program until the thread finishes (synchronization).
- Shared State Danger: Multiple threads modifying the same variable can cause “Race Conditions.”
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join() # Wait for thread to finish