What is multithreading and how does it work in Python?
sobes.tech AI
Answer from AI
Multithreading allows executing multiple threads (independent sequences of execution) within a single process. This is useful for tasks that involve waiting for input/output (e.g., reading from a file, network requests), as threads can switch while one thread is waiting.
In Python, multithreading is implemented using the threading module.
import threading
import time
def worker(num):
"""Worker thread function"""
print(f'Thread {num} started.')
time.sleep(1) # Simulate work
print(f'Thread {num} finished.')
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,)) # Create thread
threads.append(t)
t.start() # Start thread
for t in threads:
t.join() # Wait for thread to finish
print('All threads are finished.')
| Component | Description |
|---|---|
Thread |
Class for creating a new thread |
target |
Function to be executed in the thread |
args |
Tuple of arguments for the target function |
start() |
Starts the thread execution |
join() |
Waits for the thread to finish |
However, Python has the Global Interpreter Lock (GIL). GIL is a mutex that protects access to Python objects, preventing multiple native, non I/O blocking (CPU-bound) threads from executing simultaneously. This means that for CPU-intensive tasks, multithreading in Python will not lead to parallel execution on multi-core processors. For such tasks, multiprocessing is often used, which creates separate processes.
GIL does not affect threads that are waiting for input/output operations, as GIL is released during waiting. Therefore, multithreading is effective for I/O-bound tasks.