Answer the question
In order to leave comments, you need to log in
PyQt 5: how to terminate multiple QThread threads at the same time within a certain time?
Good afternoon. I have a Python 3.4 code using PyQt 5. In it, I have several threads created from the same class, inherited from QThread:
# -*- coding: utf-8 -*-
from sys import argv as sys_argv, exit as sys_exit
import time
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QThread
class Thread_Worker (QThread):
def __init__ (self):
super().__init__()
self.isRun = True
def run (self):
while self.isRun:
time.sleep(60) # Do something
class Threads_Control (QWidget):
def __init__ (self):
super().__init__()
self.threads = []
self.resize(250, 150)
self.move(200, 200)
self.show()
for i in range(50): # Создать 50 потоков
th = Thread_Worker()
self.threads.append(th) # Закинуть инстанс потока в массив
th.start()
def stop_all_threads (self):
for th in self.threads:
th.isRun = False # Установить флаг, что поток должен остановиться
if (not th.wait(5000)): # Ждать завершения потока 5 секунд
th.terminate() # Если не завершился за это время, завершить насильно
if __name__ == '__main__':
app = QApplication(sys_argv)
tc = Threads_Control()
tc.stop_all_threads()
sys_exit(app.exec_())
Answer the question
In order to leave comments, you need to log in
First, in the loop, give everyone a command to end. Out of loop, wait 5 seconds. Force them to end with the next cycle.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question