Commit ddf9e6da authored by Francois Cartegnie's avatar Francois Cartegnie

Qt: eventratelimiter: use mutex

parent 11104bf4
...@@ -21,10 +21,12 @@ ...@@ -21,10 +21,12 @@
#include <QTimer> #include <QTimer>
#include <QApplication> #include <QApplication>
#include <QMutex>
RateLimitedEventPoster::RateLimitedEventPoster( int i_millisec_interval ) RateLimitedEventPoster::RateLimitedEventPoster( int i_millisec_interval )
{ {
timer = new QTimer(); timer = new QTimer();
mutex = new QMutex();
timer->setSingleShot( true ); timer->setSingleShot( true );
/* Assuming a 24fps event loop, delays at least events to the next frame */ /* Assuming a 24fps event loop, delays at least events to the next frame */
if ( i_millisec_interval < 1 ) if ( i_millisec_interval < 1 )
...@@ -38,28 +40,39 @@ RateLimitedEventPoster::~RateLimitedEventPoster() ...@@ -38,28 +40,39 @@ RateLimitedEventPoster::~RateLimitedEventPoster()
timer->stop(); timer->stop();
commit(); commit();
delete timer; delete timer;
delete mutex;
} }
void RateLimitedEventPoster::postEvent( UniqueEvent *e, QObject *target ) void RateLimitedEventPoster::postEvent( UniqueEvent *e, QObject *target )
{ {
event_tuple newtuple = { target, e }; event_tuple newtuple = { target, e };
foreach( event_tuple tuple, eventsList ) mutex->lock();
foreach( const event_tuple & tuple, eventsList )
{ {
if ( target == tuple.target && tuple.event->equals( e ) ) if ( target == tuple.target && tuple.event->equals( e ) )
{ {
delete e; delete e;
mutex->unlock();
return; return;
} }
} }
eventsList << newtuple; eventsList << newtuple;
mutex->unlock();
if ( eventsList.count() >= 100 ) /* limit lookup time */
{
timer->stop();
commit();
}
if ( !timer->isActive() ) timer->start(); if ( !timer->isActive() ) timer->start();
} }
void RateLimitedEventPoster::commit() void RateLimitedEventPoster::commit()
{ {
foreach( event_tuple tuple, eventsList ) mutex->lock();
foreach( const event_tuple & tuple, eventsList )
{ {
QApplication::postEvent( tuple.target, tuple.event ); QApplication::postEvent( tuple.target, tuple.event );
} }
eventsList.clear(); eventsList.clear();
mutex->unlock();
} }
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
#include <QEvent> #include <QEvent>
#include <QList> #include <QList>
class QTimer; class QTimer;
class QMutex;
class UniqueEvent : public QEvent class UniqueEvent : public QEvent
{ {
...@@ -50,6 +51,7 @@ private: ...@@ -50,6 +51,7 @@ private:
}; };
QList<event_tuple> eventsList; QList<event_tuple> eventsList;
QTimer *timer; QTimer *timer;
QMutex *mutex;
}; };
#endif // UNIQUEEVENT_HPP #endif // UNIQUEEVENT_HPP
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment