Do I need to call wait() to block the thread it has no work to do for performance in Qt

I create a QThread and move some objects into it. Then I call start, but if the signal connects to the slot of object in the thread has no been emit, the thread has nothing to do. In this case, do I need to call wait() to block the thread for performance in Qt?

In other words, does the Qthread (the start function is called and it is running) consume CPU resource when there is no function runs in it?

1 answer

  • answered 2018-05-16 05:01 user3606329

    No, you don't need to sleep an idle thread for performance reasons. The resources used are so minimal that you could create serveral (hundred) empty threads on modern systems without a noticeable performance drawback on your system.

    On some systems you might want to add a minimal sleep of 10 ms, if you have an endless loop in the thread. This may have a positive effect on the CPU usage.

    EDIT: Comments state that sleeping a QThread is wrong, because they are event driven. This is not always correct.

    It entirely depends of the QThread type (e. .g. overridding QThread::run) is perfectly fine to use with an endless loop, because the QObject lives in the callers thread and slots would get executed in the callers thread. It's therefore rather used for tasks that do not need any communication.

    For long running tasks that only emit and do not receive any events overriding QThread::run + while(1) + QThread::msleep is not a wrong approach.

    If you plan to receive events you should use the QThread - worker approach and move QObject to the thread. In this case an event loop should be used.