84 lines
1.3 KiB
C++
84 lines
1.3 KiB
C++
#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<std::mutex> 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<std::mutex> l(_eventMutex);
|
|
if (_eventConsumers.size())
|
|
{
|
|
_eventQueue.push_back(eventData);
|
|
}
|
|
}
|
|
|
|
void CEventSystem::AddEventConsumer(std::function<void(const CEvent&)> 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();
|
|
}
|
|
} |