How to cancel pending(unprocessed) emitted signals
I am having an application which has one main thread and worker thread. My worker threads keep on getting data from connected server and based on data type, emits different signals to my main thread.
Is it possible in qt,that when I am emitting a new signal to main thread , I would like to clean all the pending(unprocessed) signals of that type from main thread signal queue,so that my latest signal will get processed only.
Maybe this would work:
add another worker thread
connect new worker with your worker
signal all data to new worker thread and store it in QList(QMap or what ever you'd like)
signal new worker thread from main thread when main thread ready to process new data
in new worker signal asked data from end of QList(or whatever) back to main thread
I think it is an interesting question!
In principle, Qt supports event compression. Some events like update and language change are compressed if there are multiple of these in the queue, but I can't find a public API to make any other types of events compressed, let alone modifying the compression of the events used for signals.
A work-around may be that you let your worker thread keep a set of counters to work as an identifyer for each signal you send. You give the worker a public method to retreive the last id send for a given signal type, and send the id with each signal. Then, you check for each signal you get from the worker in your main thread, if the id corresponds to the last one send.
It would be nice if the way events are compressed could be modified. That would be a very cool feature, and useful in cases like these!
Thanks a lot for your suggestions, but these workarounds are making me temptated for one more question. If I am emitting n number of signals from worker to main thread, then by implemanting any of workaround neverthless, my main thread will be processing n number of signals. However it is different case that main thread might not get any data to process for many of signals since QVector of data would be cleared off, but still main thread will retrieve the signal from queue and will check for QVector to process the data.
Can we avoid even these operations also.
I was browsing qt doc I need you people suggestion wheather this is correct or not.?
- Change signal slot to custom events(i.e. worker thread will be posting cutom events to main therad instead of signals)
- Use QApplication::removePostedEvents(QObject * sender, EventType * event), I can remove all the already posted events of this category.
Please let me know is my unsderstanding correct ?
Yeah, that should work as well, but only for the main eventloop. It is not a general solution for getting rid of signal-related event queues between threads. Note that the eventType is an int, by the way.