[SOLVED]QTimer::remainingTime() returning negative numbers diff. from -1 ?!
Hi everyone,
I'm using a QTimer in a multithread Qt5 application. Here is my structure:
Main application (MainWindow.cpp) creates a thread "ComputeScores" that creates N threads "AlgorithmTest" in its run() method. In each of these "AlgorithmTest" threads run() methods, I'm creating a timer to give to a particular algorithm some time budget (once the time is elapsed, the algorithm has to give the best answer it found during this interval).
So what I do in some of my algorithm steps to check the budget isn't exhausted is testing that the reamining time of my timer is not 0. But it turned out that QTimer has a strange behaviour...
When I start my algorithm in "AlgorithmTest" run(), the first thing I do is "myTimer.start(myBudget);". Then as second instruction, for testing purposes, I print myTimer.remainingTime() rightaway with "qDebug() << myTimer.remainingTime()".
The first time it prints (so for the first call to start()), it prints... 0. Then the second time, it prints a random negative number (always a negative one) like -613230304. So of course the rest of my program just makes everything wrong (like infinite loop as the time never reaches 0, even if sometimes it does, despite of the negative remainingTime ?!).
I just don't know what to do here, I googled that and nobody has never seen negative remaining times I think... :/
Thank you in advance!!
Re: QTimer::remainingTime() returning negative numbers diff. from -1 ?!
Show us the code please. Also remember that the timer requires a running event loop to fire. If you don't return to the event loop before the timer times out, you will not get notified that the timer has expired.
Re: QTimer::remainingTime() returning negative numbers diff. from -1 ?!
Hi thank you for your response.
You were right, the problem was the event loop that I didn't fired. Now instead of calling my code directly in run(), I just do
Code:
QTimer::SingleShot(0,
this,
SLOT(threadCode
());
exec();
and I added "quit();" at the end of threadCode(). Everything is fine now.
Re: QTimer::remainingTime() returning negative numbers diff. from -1 ?!
How does that solve your stated problem?