M
M
Maxim2017-06-12 17:38:58
Qt
Maxim, 2017-06-12 17:38:58

QThread is slow on macOS. What is the reason?

Code example:

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);

  Worker *worker = new Worker();
  QThread *thread = new QThread;
  worker->moveToThread(thread);
  QObject::connect(thread, SIGNAL(started()), observer, SLOT(doWork()));
  QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
  QObject::connect(worker, SIGNAL(finished()), worker,
                   SLOT(deleteLater()));
  QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
  thread->start(QThread::HighestPriority);

  return a.exec();
}

void Worker::doWork() {
  while (!is_stop) {
    qDebug() << count;
    count++;
    thread()->msleep(1000);
  }

  emit finished();
}

For the first 20-30 seconds, doWork() works fine, outputting every second, then the output slows down and happens every 5-10 seconds, like macOS lowers the process priority or something. What could be the reason? I tried to run as root, increase the priority of the thread, it does not help. On Linux, this code works fine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ighor July, 2017-06-12
@IGHOR

Try using a timer with QEventLoop instead of msleep.
It's better to include QThread::finished() rather than worker in deleteLater().
Yes, and a.exec(); by itself will not wait for those deletion signals, you must also thread->wait() after a.exec() and then return 0;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question