What is multithreading in Python?
a) Running multiple threads concurrently to perform tasks simultaneously
b) Running multiple processes concurrently
c) Executing a single thread multiple times
d) Running multiple functions sequentially
Answer:
a) Running multiple threads concurrently to perform tasks simultaneously
Explanation:
Multithreading in Python refers to the ability to run multiple threads concurrently within a single process. Each thread can execute a separate task, allowing for parallel execution of code, which can lead to more efficient use of system resources, especially in I/O-bound tasks.
import threading
def print_numbers():
for i in range(5):
print(i)
def print_letters():
for letter in ['A', 'B', 'C', 'D', 'E']:
print(letter)
# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting threads
thread1.start()
thread2.start()
In this example, two threads are created and started: one to print numbers and another to print letters. Both threads run concurrently, allowing both tasks to execute simultaneously.
Multithreading is commonly used in scenarios where tasks can be performed in parallel, such as handling multiple client requests in a web server or performing background tasks while maintaining a responsive user interface.