What is the best way to exit out of a loop after an elapsed time of 30ms in C++

后端 未结 9 1002
感动是毒
感动是毒 2020-12-11 13:24

What is the best way to exit out of a loop as close to 30ms as possible in C++. Polling boost:microsec_clock ? Polling QTime ? Something else?

Something like:

9条回答
  •  春和景丽
    2020-12-11 14:08

    The calculations in the loop are for updating a simulation. Every 30ms, I'd like to update the viewport.

    Have you considered using threads? What you describe seems the perfect example of why you should use threads instead of timers.

    The main process thread keeps taking care of the UI, and have a QTimer set to 30ms to update it. It locks a QMutex to have access to the data, performs the update, and releases the mutex.

    The second thread (see QThread) does the simulation. For each cycle, it locks the QMutex, does the calculations and releases the mutex when the data is in a stable state (suitable for the UI update).

    With the increasing trend on multi-core processors, you should think more and more on using threads than on using timers. Your applications automatically benefits from the increased power (multiple cores) of new processors.

提交回复
热议问题