pyside2 停止线程操作
时间: 2023-08-30 15:06:57 浏览: 133
要停止一个线程,可以通过设置一个标志位来让线程自行停止。具体来说,可以在线程类中定义一个布尔型的标志位,用于表示线程是否需要停止。在主线程中,通过修改这个标志位的值来通知线程停止。在线程的run方法中,需要定期检查这个标志位的值,如果发现标志位为True,则退出线程。
以下是一个简单的例子,演示如何使用标志位来停止一个线程:
``` python
import threading
import time
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():
print("Thread is running...")
time.sleep(1)
print("Thread stopped.")
# 创建线程并启动
t = MyThread()
t.start()
# 停止线程
time.sleep(5)
t.stop()
```
在这个例子中,我们定义了一个MyThread类,继承自threading.Thread。在该类中,我们定义了一个_stop_event事件,用于表示线程是否需要停止。在stop方法中,我们通过设置_stop_event事件来通知线程停止。在run方法中,我们在一个循环中不断检查_stop_event事件的状态,如果发现事件被设置了,则退出循环,停止线程。我们通过调用MyThread的stop方法来停止线程。
阅读全文
相关推荐


















