How do you create a thread in Python?
a) By creating an instance of the Thread class from the threading module
b) By using the multiprocessing module
c) By calling the run() method directly
d) By using the os.fork() method
Answer:
a) By creating an instance of the Thread class from the threading module
Explanation:
To create a thread in Python, you create an instance of the Thread
class from the threading
module. The thread is then started using the start()
method.
import threading
def print_hello():
print("Hello from the thread!")
# Creating a thread
thread = threading.Thread(target=print_hello)
# Starting the thread
thread.start()
# Joining the thread to wait for its completion
thread.join()
In this example, a new thread is created to execute the print_hello
function. The thread is then started and joined, ensuring that the main program waits for the thread to complete before proceeding.
Creating threads allows you to execute multiple tasks concurrently, improving the performance and responsiveness of your programs, especially in I/O-bound or CPU-bound operations.