Overview
Threading is a way to run multiple threads (smaller units of a process) concurrently within a program.
Threads share the same memory space, making them suitable for I/O-bound tasks.
Use Case
- Threads are ideal for I/O-bound tasks (e.g., file reading/writing, network requests).
- CPU-bound tasks should consider multiprocessing or asyncio.
Threading Module
import threading
import time
def print_numbers():
for i in range(10):
print(i)
time.sleep(1)
"""
Thread class represents an activity that will be run in a separate thread.
`target` specifies that print_numbers function will be executed in the new thread.
"""
thread = threading.Thread(target=print_numbers)
"""
Thread class initiates the thread's activity by calling run method in a new thread.
The run method in turn calls the target function.
"""
thread.start()
"""
join() blocks the calling thread (main thread) until the thread whose join method is called terminates.
"""
thread.join()