Important: Please read the Qt Code of Conduct -

[Solved] Busy Loop question

  • Hello guys,

    This may be more a general C++ question. I'm seeing weird behavior and I don't understand the difference between 2 loops, the loop (#1) works fine on my Win7 system, but not on Mac OS. I'm trying to understand the difference, does a infinite loops needs to do something while waiting? why does the (#2) works on Mac OS but not the (#1) ? Thanks in advance :)

    By "works" I mean the #1 loop doesn't break even when it should, but when using a dummy debug it breaks..

    @ while (!allChannelClosed && antThreadRunning) {

    @ while (!allChannelClosed && antThreadRunning) {
    qDebug() << "waiting...";

  • Booth loops are busy-loops and eat cpu like cookie-monster eats the cookies.
    Check CPU usage when you have it running.

    If you change the conditional variables in another thread then loop #1 is so busy that it does not give any chance to anybody to interrupt it and update the variables.
    The qDebug() line gives a little time to other thread to update the variables.

    Each OS handles such busy-loops differently that is why it works on Win7 and does not work on OSX.

    I would suggest to use conditional wait in the loop to avoid high CPU usage and to use mutexes to protect the conditional variables.

  • Thanks again for your help andreyc.

    Yes this kind of busy loop is probably a bad idea, I'll have to rethink it.
    Basically this busy loop is taking place in another thread that is controlled from my mainApp. When mainApp change the value of the boolean in the thread, I want to stop the busy loop (end thread execution). But the thread has another thread inside it so it's a bit complicated.

    I will take a look at Signal and slot, I can probably send a signal to the thread to stop it, but still it will need to have a busy loop so it doesn't terminate it works before mainApp asks him.

    Another solution could be to add a "Sleep" inside the busy-loop so that it eats less CPU? I don't need it to be 1ms reactive, I could stop it with 1sec delay and be fine. I was wondering why my room was eating up so much, now I know why :)

  • fixed by adding "QThread::sleep(1);" in the loop

Log in to reply