gpt4 book ai didi

python - 如何杀死正在运行的线程

转载 作者:行者123 更新时间:2023-11-28 22:17:40 25 4
gpt4 key购买 nike

我有一个对话框显示正在运行的线程的进度:

from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from PyQt5.QtCore import *

class LoaderProgress(QDialog):
def __init__(self, parent=None):
super(LoaderProgress, self).__init__(parent)
loadUi("CliReportsUI/loaderprogress.ui", self)
self.pbLoader.setValue(0)
self.btn_cancel.clicked.connect(self.killthread)

def watchthread(self,worker):
self.thread = worker(self)
self.thread.totsignal.connect(self.pbLoader.setMaximum)
self.thread.cntsignal.connect(self.updateprogress)
self.thread.finished.connect(self.close)

def settitle(self,title):
self.setWindowTitle(title)

def startthread(self):
self.thread.start()

def updateprogress(self,n):
self.pbLoader.setValue(n)

def killthread(self):
print('How do I do this')

另一个类中的方法以下列方式运行线程:

    dlg = LoaderProgress(self)
dlg.watchthread(FileLoader)
dlg.settitle("Loading The Master File...")
dlg.show()
dlg.startthread()

然后是 worker 类(Class):

class FileLoader(QThread):
totsignal = pyqtSignal(int)
cntsignal = pyqtSignal(int)

def __init__(self,parent=None):
super(FileLoader, self).__init__(parent)
self.threadactive = True
self.total = 100

def run(self):
self.totsignal.emit(self.total)
i = 1
while(i < self.total and self.threadactive):
print(time.time)
if(time.time() % 1==0):
i+=1
self.cntsignal.emit(i)

在加载程序对话框中,我有一个取消进程的按钮 (btn_cancel),但我不知道如果单击取消按钮如何终止正在运行的线程。感谢您的帮助。

最佳答案

您必须实现一个 stop() 方法,将 threadactive 标志更改为 False 并使用 wait 等待术语()

class FileLoader(QThread):
totsignal = pyqtSignal(int)
cntsignal = pyqtSignal(int)

def __init__(self,parent=None):
super(FileLoader, self).__init__(parent)
self.threadactive = True
self.total = 100

def run(self):
self.totsignal.emit(self.total)
i = 1
while(i < self.total and self.threadactive):
print(time.time())
if(time.time() % 1==0):
i+=1
self.cntsignal.emit(i)

def stop(self):
self.threadactive = False
self.wait()

然后在killthread 方法中调用它:

def killthread(self):
self.thread.stop()
print('How do I do this')

关于python - 如何杀死正在运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com