Home > Back-end >  How to keep a count of active Python and Qt threads
How to keep a count of active Python and Qt threads

Time:06-07

I did a code with PyQt (appended below) which is supposed to create threads and count how many of them are active when you click a button. Since there is a time.sleep(1) inside each thread, i should be able to click the button fast enough so that the active_threads count would increase before diminishing when each thread is finished.

However, no matter how fast i click the button i see only the number 1 printed on the terminal. I looked at the threading documentation and about active_count() it says:

Return the number of Thread objects currently alive.

So i suppose QThreads do not use thread objects, but some other implementation. I found nothing about counting QThreads in the QThread class documentation. What is the best strategy? Is there anything better than storing threads in a list and removing them of the list at the end?

Code:

#!/usr/bin/python3

import sys, threading, time

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import QThread

threads=[]

class Example(QThread):

    def run(self):
        print(threading.active_count())
        time.sleep(1)

def thread_creator():
    new_thread=Example()
    threads.append(new_thread)
    new_thread.start()

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('QHBoxLayout')
layout = QHBoxLayout()
my_widget=QPushButton('Eat healthy!')
my_widget.clicked.connect(thread_creator)
layout.addWidget(my_widget)
window.setLayout(layout)
window.show()

sys.exit(app.exec_())

CodePudding user response:

Both Thread and QThread are just wrapper objects for managing system threads. As the Python documentation you quoted states, active_count is a count of Python Thread objects, not system threads. Obviously there may be many other threads active on your system that were created by other processes, or by other libraries used by your program (such as Qt). So you need to decide which particular subset of threads to count. Qt may create threads internally in addition to the ones you created yourself, so you may not want to count those as well...

If you want to count only those threads you started yourself, you already have active_count for the Python threads. For the Qt ones, you could use QThreadPool. Another possibility might be to use a central queue which could be accessed by all your threads.

  • Related