thredPool_02.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# -*- coding: utf-8 -*-
import sys
import time
import datetime
import random

from PySide2 import QtCore, QtWidgets


class WorkerSignal(QtCore.QObject):

    finished = QtCore.Signal(object)
    sendLog = QtCore.Signal(str)

    def __init__(self):
        super().__init__()


class Worker(QtCore.QRunnable):

    def __init__(self, threadId, count=10):
        super().__init__()

        self.threadId = threadId
        self.count = count
        self.signals = WorkerSignal()
        self._stop = False

    def stopThread(self):

        self._stop = True

    def run(self):

        if self._stop:
            return

        for i in range(self.count):
            self.signals.sendLog.emit(f"{self.threadId} -> 残り{str(self.count - i)}")
            time.sleep(1)
            if self._stop:
                break

        self.signals.finished.emit(self)


class SampleDialog(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super().__init__(parent)

        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)

        self.view = QtWidgets.QListView(self)
        layout.addWidget(self.view)
        self.model = QtCore.QStringListModel()
        self.view.setModel(self.model)

        self.line = QtWidgets.QLabel()
        layout.addWidget(self.line)

        btn = QtWidgets.QPushButton("Start")
        btn.clicked.connect(self.push)
        layout.addWidget(btn)

        self.pool = QtCore.QThreadPool()
        self.pool.setMaxThreadCount(5)
        self.workers = {}

    def closeEvent(self, e):

        for i in self.workers:
            self.workers[i].stopThread()
        self.pool.waitForDone()

    def updateThreadCountUI(self):

        activeThreadCount = self.pool.activeThreadCount()
        message = f"実行中のスレッド数 {str(activeThreadCount)} 待機スレッド {str(len(self.workers) - activeThreadCount)}"
        self.line.setText(message)

    def showMessage(self, message):

        messages = self.model.stringList()
        messages.append(message)
        self.model.setStringList(messages)

    def push(self):

        for i in range(10):

            threadID = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S_%f_') + str(i)  # 今の日付をKeyにする

            self.workers[threadID] = Worker(threadID, random.randint(1, 10))
            self.workers[threadID].signals.finished.connect(self.finishTask)
            self.workers[threadID].signals.sendLog.connect(self.showMessage)
            self.workers[threadID].setAutoDelete(True)
            self.pool.start(self.workers[threadID])

        self.updateThreadCountUI()

    def finishTask(self, worker):

        self.showMessage(f'finish task -> {worker.threadId}')
        self.workers.pop(worker.threadId)
        self.updateThreadCountUI()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    ui = SampleDialog()
    ui.show()

    sys.exit(app.exec_())

最終更新日: 2022-06-15 15:27:01