Junior — Middle
In what cases is multithreading used in programming?
sobes.tech AI
Answer from AI
Multithreading is used when it is necessary to perform multiple tasks simultaneously to improve the performance or responsiveness of a program. In Python, this is useful for:
- Performing input/output operations (such as network requests, file handling), where threads can wait for operations to complete without blocking the entire program.
- Parallel processing of tasks that do not require intensive computation (due to GIL in CPython).
- Improving the responsiveness of user interfaces so that heavy operations do not block the main thread.
An example of using multithreading for parallel downloading of multiple files:
import threading
import requests
def download(url):
resp = requests.get(url)
print(f"Downloaded {len(resp.content)} bytes from {url}")
urls = ["https://example.com/file1", "https://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()