如何监控Qt信号事件队列深度

时间:2017-06-08 16:02:57

标签: c++ multithreading qt qt5

我的程序中有两个对象。一个目标是发射信号。另一个接收插槽中的信号并逐个处理输入信号。两个对象都在不同的线程中运行。现在我需要测量和监控接收对象的工作量。

问题是我不知道有多少信号等待我的第二个对象在Qt信号队列中处理。有没有办法获得这个队列的大小?或者是否有工作要知道还有多少信号仍需要保留?

1 个答案:

答案 0 :(得分:4)

qGlobalPostedEventsCount()是一个起点,虽然它只适用于当前线程。

要轮询任意线程,我们可以使用Qt的内部。然后实现非常简单。即使线程被阻止并且不处理事件,它也能工作。

// https://github.com/KubaO/stackoverflown/tree/master/questions/queue-poll-44440584
#include <QtCore>
#include <private/qthread_p.h>
#include <climits>

uint postedEventsCountForThread(QThread * thread) {
   if (!thread)
      return -1;
   auto threadData = QThreadData::get2(thread);
   QMutexLocker lock(&threadData->postEventList.mutex);
   return threadData->postEventList.size() - threadData->postEventList.startOffset;
}

uint postedEventsCountFor(QObject * target) {
   return postedEventsCountForThread(target->thread());
}

如果真的希望不使用私有API,我们可以使用更简单的解决方案来增加开销。首先,让我们回想起最低开销意味着在某个对象的线程中进行操作&#34;是要说&#34;东西&#34;在一个事件的析构函数中 - 见this answer for more details。我们可以将最高优先级事件发布到目标对象的事件队列。该事件包含一个调用qGlobalPostedEventsCount的任务,更新count变量,并释放我们随后获取的互斥锁。在获取互斥锁时,计数具有返回的有效值。如果目标线程没有响应且请求超时,则返回-1

uint qGlobalPostedEventsCount(); // exported in Qt but not declared
uint postedEventsCountForPublic(QObject * target, int timeout = 1000) {
   uint count = -1;
   QMutex mutex;
   struct Event : QEvent {
      QMutex & mutex;
      QMutexLocker lock;
      uint & count;
      Event(QMutex & mutex, uint & count) :
         QEvent(QEvent::None), mutex(mutex), lock(&mutex), count(count) {}
      ~Event() {
         count = qGlobalPostedEventsCount();
      }
   };
   QCoreApplication::postEvent(target, new Event(mutex, count), INT_MAX);
   if (mutex.tryLock(timeout)) {
      mutex.unlock();
      return count;
   }
   return -1;
}

测试工具:

int main(int argc, char ** argv) {
   QCoreApplication app(argc, argv);
   struct Receiver : QObject {
      bool event(QEvent *event) override {
         if (event->type() == QEvent::User)
            QThread::currentThread()->quit();
         return QObject::event(event);
      }
   } obj;
   struct Thread : QThread {
      QMutex mutex;
      Thread() { mutex.lock(); }
      void run() override {
         QMutexLocker lock(&mutex);
         QThread::run();
      }
   } thread;
   thread.start();
   obj.moveToThread(&thread);
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::User));
   auto count1 = postedEventsCountFor(&obj);
   thread.mutex.unlock();
   auto count2 = postedEventsCountForPublic(&obj);
   thread.wait();
   auto count3 = postedEventsCountFor(&obj);
   Q_ASSERT(count1 == 4);
   Q_ASSERT(count2 == 4);
   Q_ASSERT(count3 == 0);
}
QT = core-private
CONFIG += console c++11
CONFIG -= app_bundle
TARGET = queue-poll-44440584
TEMPLATE = app
SOURCES += main.cpp