56 lines
No EOL
1.5 KiB
C++
56 lines
No EOL
1.5 KiB
C++
/*******************************************************************************
|
|
Copyright © 2017 Philips Lighting Holding B.V.
|
|
All Rights Reserved.
|
|
********************************************************************************/
|
|
|
|
#include <iostream>
|
|
#include "MessageDispatcher.h"
|
|
namespace huestream {
|
|
MessageDispatcher::MessageDispatcher():
|
|
_queue(),
|
|
_condition(),
|
|
_isRunning(false), _mutex() {
|
|
};
|
|
|
|
void MessageDispatcher::Queue(DispatchAction action) {
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
_queue.insert(_queue.begin(), action);
|
|
lock.unlock();
|
|
_condition.notify_all();
|
|
};
|
|
|
|
void MessageDispatcher::Execute(bool useThisTread) {
|
|
_isRunning = true;
|
|
|
|
if (useThisTread) {
|
|
Loop();
|
|
} else {
|
|
huesdk_lib::ThreadTask task = [this]() -> void { Loop(); };
|
|
_thread = std::unique_ptr<huesdk_lib::Thread>(new huesdk_lib::Thread(task));
|
|
}
|
|
}
|
|
|
|
void MessageDispatcher::Loop() {
|
|
|
|
while (true) {
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
_condition.wait(lock, [this]() -> bool { return _queue.size() != 0 || !_isRunning; });
|
|
if (!_isRunning)
|
|
return;
|
|
auto action = _queue.back();
|
|
_queue.pop_back();
|
|
lock.unlock();
|
|
action();
|
|
}
|
|
}
|
|
|
|
void MessageDispatcher::Stop() {
|
|
_isRunning = false;
|
|
_condition.notify_all();
|
|
if (_thread != nullptr) {
|
|
_thread->join();
|
|
_thread.reset();
|
|
}
|
|
}
|
|
|
|
} |