Error getting current time
is freezing my application.
i would also suggest not to cast an int to QString like you do.
there are several ways to convert it “a nice” way like
But for QTime the best way is defenatly the way anselmolsm suggested with .toString() and the formatting.
Actually, with some more debugging, I think I figured out the problem:
The application appears to be frozen because the while loop is running on the same thread as the UI.
Now the problem is that I am building this program on an old computer with only one processor core. I will be deploying it to an even older computer, which surely has only one processor core. How can I do multi-threading on a single processor computer? If I can’t, then is there another workaround?
you can surly put it to another thread. Having several CPUs only means a several Thread can work at the same time. On a single CPU computer threads are executed sequencialy. Means a bit of Thread A a bit of Thread B a bit of Thread A again etc…
Every thread gets an own short time slice. So in your case two threads would just rotate cpu usage, what would stop freezing your gui. But an important thing here is, you should not request the checkstate in another Thread than gui thread. You should connect the stateChanged signal to a slot in the thread to change an bool to abort the while loop. Manipulating gui elements in a non gui Thread doesnt work. Also you should add a little sleep timer (QThread::wait) no save cpu resources since it will be an old computer like you said.
Okay. Now my code looks like this:
You are doing a busy waiting loop threre and even if you put that into a different thread it will use lots of CPU (and drain batteries of your laptop/mobile).
Why don’t you use a QTimer to trigger a slot every x seconds (where x is between 1 and 60 in your case)? And why on earth are you turing the time returned by
Felix: Using a QTimer here is not dirty, it is the right thing to do. Busy waiting has some uses in the kernel of an OS, but should (in an ideal world at least;-) never be necessary in user space applications.
Sleeping in a thread can miss the deadline, too! You don’t really win anything by adding the complexity of threads.
Just use a timer with a resolution fine enough for your need and use
- a.SecsTo(b) <= 0
Please keep in mind that waking up a CPU is expensive, so the shorter your wait interval the more expensive your application gets. This is especially true for battery powered devices: Each wakeup forces the CPU into a high power state!
The issue is not about waking up the thread: Your code never put it to sleep! It is busily comparing times as often as possible.
Actually putting the thread to sleep will help. In fact having a timer or a sleeping thread does not really make a difference (when the timer interval and the sleep time are equal).