#include "stdafx.h" #include "EventSystem.h" using namespace Sia::Api; CEventSystem CEventSystem::EventSystem; CEventSystem::CEventSystem() : _stopEvent(INVALID_HANDLE_VALUE) { } CEventSystem::~CEventSystem() { Stop(); ::CloseHandle(_stopEvent); } void CEventSystem::ProcessEvents() { while (::WaitForSingleObject(_stopEvent, 10) == WAIT_TIMEOUT) { CEventPtr eventData; do { { std::lock_guard l(_eventMutex); if (_eventQueue.size()) { eventData = _eventQueue.front(); _eventQueue.pop_front(); } else { eventData.reset(); } } if (eventData) { for (auto& v : _eventConsumers) { v(*eventData); } } } while (eventData); } } void CEventSystem::NotifyEvent(CEventPtr eventData) { std::lock_guard l(_eventMutex); if (_eventConsumers.size()) { _eventQueue.push_back(eventData); } } void CEventSystem::AddEventConsumer(std::function consumer) { if (!_processThread) { _eventConsumers.push_back(consumer); } } void CEventSystem::Start() { if (!_processThread) { _stopEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr); _processThread.reset(new std::thread([this]() {ProcessEvents(); })); } } void CEventSystem::Stop() { if (_processThread) { ::SetEvent(_stopEvent); _processThread->join(); _processThread.reset(); } }