Solved QElapsed does not work in a separate thread
-
Hello,
I'm trying to use a QElapsedTimer inside a std::thread to send processed data at regular time intervals in a way similar to the code below. Unfortunately the method elapsed() return alway 0. Can anybody help me?void MyClass::ConsumerThread() { QElapsedTimer elapsedTimer; elapsedTimer.start(); while (!queue.isEmpty()) { // <dequeue, process and accumulate> Q_ASSERT(elapsedTimer.isValid()); if (elapsedTimer.elapsed() > 500) // elapsed() returns always 0 { // ==> send processed data elapsedTimer.restart(); } } }
-
This is strange, can you try with
std::chrono
(example at the bottom of this page) and see if the same happens? -
@VRonin Thank you for your answer, with std::chrono doesn't work the same but something is slight different, so I have found the bug.
The thread processing time in my test (really low data rate respect to production) it takes only few milliseconds, so the elapsed is not detected. The QElapsedTime version return always 0, the std::chrono most of the times 0 but sometimes 1 or 2ms (maybe is more precise or the std::chrono version consumes moretime). -
If the processing time is less than one millisecond you could use "nsecsElapsed()" instead.
-
I have used to QElapsedTimer in a thread to monitor network code. However, the times I monitored were anywhere from 15 seconds to 500mS. So it does work fine in threads.
-
@fcarney I'm using a lot of QElapsedTimer objects into a lot of threads without any problem.