반응형
    
    
    
  pyside 앱에서 여러 개의 스레드를 사용하다보면 도대체 현재 몇 개의 스레드가 활성화되어 있는지 궁금할 때가 있다. QThreadPool을 활용하면 활성화되어 있는 스레드의 개수를 파악할 수 있다.
QThreadPool은 스레드를 사용하는 프로그램에서 스레드 생성 비용을 줄이기 위해 개별 QThread 객체를 관리하고 재활용하기 위해 사용된다 [1].
예제를 위해 간단한 프로그램을 만들었다. 하나의 버튼이 있는 프로그램인데, 버튼을 클릭하면 하나의 스레드가 생성되면서 현재 활성화되어 있는 스레드의 개수를 알려준다. 참고로 time.sleep(5)를 줬기 때문에 각 스레드는 5초 후에 소멸된다.
from PySide6.QtWidgets import QApplication, QPushButton, QHBoxLayout, QWidget
from PySide6.QtCore import QThread, QThreadPool, QRunnable
import sys
import time
class HelloWorldTask(QRunnable):
    def run(self):
        print("Hello world from thread", QThread.currentThread())
        time.sleep(5)
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        QThreadPool.globalInstance().setMaxThreadCount(100)
        self.btn1 = QPushButton("btn1")
        self.btn1.clicked.connect(self.btn1_clicked)
        
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.btn1)
        self.setLayout(self.layout)
        self.show()
    
    def btn1_clicked(self):
        hello = HelloWorldTask()
        # QThreadPool takes ownership and deletes 'hello' automatically
        QThreadPool.globalInstance().start(hello)
        print("활성 쓰레드 개수:", QThreadPool.globalInstance().activeThreadCount())
    
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec()
위 코드를 실행하면 다음과 같이 버튼이 하나 있는 프로그램 창이 열린다.

버튼을 연속해서 클릭하면 콘솔창에 다음과 같은 내용이 출력된다.

"활성 쓰레드 개수: 15"에서 "활성 쓰레드 개수: 1"이 된 이유는 버튼을 15번 클릭한 후에 잠시 쉬었다가 클릭을 했기 때문에 이전에 생성되었던 스레드가 소멸되었기 때문이다.
참고자료
[1] https://doc.qt.io/qtforpython-5/PySide2/QtCore/QThreadPool.html
[2] https://www.pythonguis.com/tutorials/multithreading-pyqt-applications-qthreadpool/, pythonguis, "Multithreading PyQt5 applications with QThreadPool"
'Dev > python' 카테고리의 다른 글
| [pyqt5] 야구 중계에 스트라이크 존이 제공되지 않을 때 시청자를 위한 가이드 앱 (2) | 2022.03.16 | 
|---|---|
| [python] 파이썬스럽게 코딩하는 법, PEP8 정리 (4) | 2022.03.15 | 
| [pyside6] QLabel에 이미지 넣을 때 종횡비(aspect ratio) 설정 (2) | 2022.02.27 | 
| [pyside6] 위젯 내 글자 크기를 변경하고 싶을 때 (0) | 2022.02.26 | 
| [flask+jinja2] 서버에서 받은 html 요소가 html 문서에서 제대로 표현되게 하려면? (0) | 2022.02.06 | 
| [flask+jinja2] break 사용하기 (2) | 2022.02.05 | 
| [python] SyntaxError: Non-ASCII character '\xec' 에러 해결법 (0) | 2022.01.14 | 
| [PySide6] DeprecationWarning: Fuction: 'globalPos() const' is marked as deprecated 경고 메시지 출력 안되게 하기 (0) | 2021.11.29 |