如何安全的终止一个无限循环线程
时间: 2024-06-14 16:03:26 浏览: 12
可以使用标志位来安全地终止一个无限循环线程。在主线程中设置一个标志位,当需要终止子线程时,将标志位设置为True。在子线程中,使用while循环来不断检查标志位,如果标志位为True,则退出循环,结束线程。下面是一个示例代码:
```python
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self._stop_event = threading.Event()
def run(self):
while not self._stop_event.is_set():
print("Thread is running...")
time.sleep(1)
print("Thread is stopped.")
def stop(self):
self._stop_event.set()
t = MyThread()
t.start()
time.sleep(5)
t.stop()
```
在这个示例代码中,我们定义了一个MyThread类,继承自threading.Thread类。在MyThread类的构造函数中,我们创建了一个Event对象,用于设置标志位。在run方法中,我们使用while循环来不断检查标志位,如果标志位为True,则退出循环,结束线程。在stop方法中,我们设置标志位为True,以便在主线程中终止子线程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)