R
R
RealL_HarDCorE2015-05-07 16:30:20
Python
RealL_HarDCorE, 2015-05-07 16:30:20

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_())

How I would like it to work: 50 threads are created, each of which has an isRun flag, which is responsible for whether the thread should continue running or not. Then, when it is necessary to complete them all, we change the flag for each of them to False, and immediately give each of them 5 seconds to correctly complete the work. If it hasn't finished in 5 seconds, forcefully terminate with the terminate() method .
The problem is that the worker's wait(5000) method blocks the main thread for the specified time (5 seconds, in my case) at each iteration of the loop.
In the worst case, it will take 50 * 5 = 250 seconds to complete 50 running threads that could not complete themselves in 5 seconds, that is, more than 4 minutes, which is absolutely not acceptable.
Can you please tell me how to tell all 50 threads at the same time that they must complete within 5 seconds?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2015-05-07
@ReaL_HarDCorE

QTimer?

P
PythonDeveloper, 2017-05-22
@PythonDeveloper

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 question

Ask a Question

731 491 924 answers to any question