Infinite loop and signal deluge
I have a problem with a loop in my code.
Basically I do this in a thread:
- while( !stop )
- textResult = someLongProcessing(); // this takes ~50ms
- emit displayText(textResult);
The problem is that sometimes someLongProcessing() returns immediately, causing the loop to emit a lot of signals.
My ram usage then increases a lot and the software crashes.
I can’t call processEvents() because I’m not in the main thread. Then what should I do?
I can not handle the issue slot-side, since it’s a qt slot.
If I add a sleep(5) in the loop it’s better, but how would I know that the computer it’s running on will need 5 or 10ms or even more to handle the setValue()…?
Thanks a lot for the help.
- EDIT: I just found about Qt::BlockingQueuedConnection, could this be a good idea?
I would simply make sure that you don’t emit your signal if it should not emit. Best place to stop such an overflow it as the source…
Is there some way for your process to know if the result is new or updated or something like that? If not, you could use a technique like this [developer.qt.nokia.com] to throttle your signal emissions, I guess.
From that thread you have no influence on the main thread directly by calling processEvents etc. If you fill up the queue of one thread by another one, you have to think, whether it is the correct way for doing so.
Perhaps you should change the logic to something like this:
thread —> setText on intermediatObject —> emit signal
intermediatObject is a thread save object, which stores the last text and stores, whether the text was already read. If a text is set, it emits the signal, if after the last read there came no new text.
But that changes the logic completely…
Another consideration is that the text might change quickly enough for the user not even to notice it. It would probably make sense to not let the longProcessThingy() control the text the user sees unless there’s an error of sorts. The current approach seems indeed too naive for successful operation.