[PyQt] QRunnable / activeThreadCount() issue

Hazen Babcock hbabcock at mac.com
Fri Jul 7 12:22:51 BST 2017


Hello,

I'm not sure if this is the expected behavior or not, but the following 
will almost always freeze up at the call to 
threadpool.activeThreadCount() after a random number of iterations due I 
assume to some issue with Python / Qt memory management. If I use 
setAutoDelete(False) and keep references to the QRunnables then the 
problem goes away. I've observed this behavior on both a linux and a 
Windows 7 platform.

#!/usr/bin/env python
"""
Test activeThreadCount() freezing.
"""
import sys
import time

from PyQt5 import QtCore, QtGui, QtWidgets


class TestRunnable(QtCore.QRunnable):

     def __init__(self, n_id, **kwds):
         super().__init__(**kwds)
         self.n_id = n_id
         self.processed = False

     def isProcessed(self):
         return self.processed

     def run(self):
         time.sleep(0.05)
         self.processed = True
         print("done", self.n_id)


class TestWidget(QtWidgets.QWidget):

     def __init__(self, **kwds):
         super().__init__(**kwds)
         self.n_started = 0
         self.threadpool = QtCore.QThreadPool()

         self.timer = QtCore.QTimer()
         self.timer.setSingleShot(True)
         self.timer.timeout.connect(self.runTest)
         self.timer.start(100)

     def runTest(self):
         i = 0
         while (self.n_started < 1000):

             # Try and start a new job.
             print("-")
             if(self.threadpool.activeThreadCount() < 4):
                 print("start", self.n_started)
                 self.threadpool.start(TestRunnable(self.n_started))
                 self.n_started += 1
             print(i, self.n_started)
             i += 1

         self.threadpool.waitForDone()
         self.close()
         print("test done")


app = QtWidgets.QApplication(sys.argv)
widget = TestWidget()
#widget.show()
app.exec_()


-Hazen


More information about the PyQt mailing list