Signal/slot across threads - remove duplicate events in event loop
I have several signal/slot connections between a worker thread and the GUI thread. Using the default delivery method, which posts an event in the GUI’s event queue, one of my connections can occasionally emit signals faster into the event queue than the slot being called. So what happens is multiple signals are being queue that are just repeats and the queue gets backed up. Is there a method to ensure that only one signal (event) is in the queue at a time?
As far as I know, there is no such method.
I think it would be best the throttle the number of messages you are sending at the source. The best performance of multi-threaded applications can be reached if you communicate as little as possible between threads. They should be as independent as possible. Do you really need to send updates to the GUI thread that fast?
In the past, I have throttled the delivery of update messages from a worker to the GUI thread to at most two per second, and that worked very well for me.
To use QCoreApplication::removePostedEvents(), you could create a custom event. Then the event type would be known.
You may also consider communicating through an atomic flag. The receiver could then poll when it is able to handle information from the worker thread.
Of course neither of these methods are as convenient as signals/slots.
I think that if you have to deliver so much events as so fast rates you have to build your own event queue, that will notify (via signals) your GUI thread once at a time and the GUI thread will process (consume) all of the events in the queue. So the queue will work as a concentrator for the incoming events: the sender thread will post events, the queue will store and present them in a block to the GUI thread when this is signalled.
Perhaps you can use the technique I described here [developer.qt.nokia.com] to limit the number of signals going down the event queue. Interesting to see that it actually is possible to manipulate the contents of the eventqueue.