What are the phases of a thread’s life cycle in Python?
a) New, Runnable, Running, Blocked, Terminated
b) Created, Waiting, Executing, Sleeping, Finished
c) Initialized, Started, Paused, Resumed, Stopped
d) Ready, Running, Sleeping, Dead, Alive
Answer:
a) New, Runnable, Running, Blocked, Terminated
Explanation:
A thread in Python goes through several phases during its life cycle:
- New: The thread is created but has not yet started execution.
- Runnable: The thread is ready to run and waiting for CPU time.
- Running: The thread is currently executing.
- Blocked: The thread is blocked and waiting for a resource (like I/O) or another thread to release a lock.
- Terminated: The thread has completed execution and is no longer running.
import threading
import time
def thread_task():
print("Thread started")
time.sleep(2)
print("Thread completed")
# Creating and starting a thread
thread = threading.Thread(target=thread_task)
print("Thread state: New (before start)")
thread.start()
print("Thread state: Runnable/Running (after start)")
thread.join()
print("Thread state: Terminated (after join)")
In this example, a thread is created, started, and joined, illustrating the different phases of its life cycle. After the thread is joined, it enters the terminated state.
Understanding the thread life cycle helps in managing and optimizing multithreaded applications, ensuring that resources are used efficiently and that threads are properly synchronized.