#ifndef __BASICEVENTHEAP_H_INCL__ #define __BASICEVENTHEAP_H_INCL__ #include "basicEvent.h" #include "basicEventHandler.h" #include "basicLogCollection.h" #include "basicMutex.h" #include "basicThread.h" #include #include typedef std::vector V_EVT_HANDLER; // How long removeHandler() / pause() wait for a running dispatchEvent() before giving up (logged) #define EVENT_HEAP_WAIT_DISPATCH_MS 5000 /** * @Description Singleton class to manage Events in the System * * Handlers are called WITHOUT the handler list locked, so a dispatchEvent() may create or delete * handlers (add/removeHandler) and another thread may delete a handler while events are dispatched: * removeHandler() returns only once the heap no longer calls that handler. * * Shutdown: pause() stops the dispatching (after the running dispatch finished) so objects can be * deleted safely, resume() continues, clearQueue() drops what was not delivered, * destroyInstance() stops the thread for good. * * @author Gagua */ class basicEventHeap : public basicThread { private: basicLogCollection * m_pLog; basicMutex * m_pDispatchingMutex; // event queue std::mutex m_mHandlers; // m_vHandlers, m_pCurrentHandler, m_bPaused, m_bInDispatch std::condition_variable m_cvDispatch; // signalled when a handler call or a dispatch round ends V_EVT_HANDLER m_vHandlers; basicEventHandler * m_pCurrentHandler; // handler being called right now (NULL if none) bool m_bPaused; bool m_bInDispatch; // an event is being dispatched pthread_t m_tDispatchThread; pEventQueue m_vEventQueue; bool isDispatchThread(void); bool isRegistered(basicEventHandler * handler); // m_mHandlers held public: static basicEventHeap * getInstance(); // The instance if it exists, NULL otherwise (never creates one) static basicEventHeap * existingInstance(); // Stops the dispatch thread and drops undelivered events (end of the application) static void destroyInstance(); virtual ~basicEventHeap(); void addHandler(basicEventHandler * handler, bool atBottom = false); void removeHandler(basicEventHandler * handler); void broadcast(EVENT_CONTAINER * Evt); void moveHandlerBottom(basicEventHandler * handler); void moveHandlerTop(basicEventHandler * handler); // Waits (up to timeoutMs) until every queued event is delivered; false on timeout bool flush(uint32_t timeoutMs = 2000); // Stops dispatching; returns once the running dispatch round ended (false on timeout) bool pause(void); void resume(void); // Releases all events still queued (not delivered); returns how many size_t clearQueue(void); protected: basicEventHeap(); void m_fThreadProc(void); private: static basicEventHeap * _instance; static std::mutex _instanceLock; // getInstance() may be called from several threads at once }; #endif // __BASICEVENTHEAP_H_INCL__