How do you stop a thread using threading.Thread in Python?
In Python, you can stop a thread’s execution by setting a flag. An example is shown below:
import threading
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def run(self):
while not self._stop_event.is_set():
# 线程的执行逻辑
pass
# 创建并启动线程
thread = MyThread()
thread.start()
# 停止线程
thread.stop()
In the above example, the MyThread class inherits from the threading.Thread class and overrides the run method as the thread’s execution logic. Within the run method, it checks the status of the _stop_event flag to determine whether to continue executing the task.
By invoking the stop method, the _stop_event flag can be set to halt the execution of the thread.