Intern — Junior
Are you aware of the concept of multithreading and its application?
sobes.tech AI
Answer from AI
Multithreading is the ability of a program to execute multiple threads (independent sequences of instructions) simultaneously, which helps improve resource utilization efficiency, especially on multi-core processors.
In Python, multithreading is often used for input/output-bound tasks (such as network requests, file operations) to avoid blocking the main execution thread.
Example of using multithreading in Python with the threading module:
import threading
import time
def worker(num):
print(f"Thread {num} started")
time.sleep(2)
print(f"Thread {num} finished")
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All threads are finished")
This example launches three threads that run the worker function in parallel. Multithreading helps improve responsiveness and performance of programs, especially when waiting for external operations.