Junior — Middle
For which use cases is the multithreading module in Python designed?
sobes.tech AI
Answer from AI
The multithreading module in Python (threading) is designed for scenarios where tasks related to input/output (I/O-bound) need to be executed in parallel, such as:
- Handling network requests
- Reading and writing files
- Interacting with databases
- Waiting for responses from external services
Due to the GIL, multithreading is inefficient for CPU-bound tasks (heavy computations), as threads do not execute in parallel on multiple cores. For such tasks, multiprocessing is a better choice.
Example of using threading for parallel file downloading:
import threading
import requests
def download(url):
resp = requests.get(url)
print(f"Downloaded {url} with {len(resp.content)} bytes")
urls = ["http://example.com/file1", "http://example.com/file2"]
threads = []
for url in urls:
t = threading.Thread(target=download, args=(url,))
t.start()
threads.append(t)
for t in threads:
t.join()