Managing Thread Lifecycles in Python: Starting and Stopping Worker Threads
Python's threading module facilitates concurrent task execution. A common requirement is too initiate a background thread and later halt its execution based on program logic.
Initiating a Worker Thread
To start a separate thread, define a target function and instantiate a Thread object.
import threading
import time
def background_operation():
while True:
print("Background task executing...")
time.sleep(1)
# Create and start the thread
worker = threading.Thread(target=background_operation)
worker.start()
This code defines background_operation as an infinite loop and launches it in a new thread.
Gracefully Terminating a Thread
Python threads cannot be forcibly killed. A cooperative approach using a control flag is standard practice.
import threading
import time
# Shared flag for thread control
should_continue = True
def controlled_task():
global should_continue
while should_continue:
print("Controlled task is active...")
time.sleep(1)
print("Task received stop signal.")
# Launch the thread
worker_thread = threading.Thread(target=controlled_task)
worker_thread.start()
# Allow the thread to run for a period
print("Main thread running...")
time.sleep(5)
# Signal the thread to stop
print("Main thread signaling stop...")
should_continue = False
# Wait for the thread to finish
worker_thread.join()
print("Worker thread has terminated.")
In this pattern, the main thread sets the global should_continue flag to False. The worker thread checks this flag on each loop iteration and exits cleanly when it becomes False. The join() method ensures the main thread waits for the worker's complesion.