threading again

This commit is contained in:
Jonas Zeunert
2018-05-06 23:19:02 +02:00
parent c2fb59139b
commit c1a29d8bea
11 changed files with 20856 additions and 24 deletions

View File

@@ -17,40 +17,65 @@ namespace Input
{
Detector::Detector(std::map<std::string, char> input_config, std::map<char, InputEvent> events) :
gpio(input_config), input_events(events)
gpio(input_config), input_events(events), is_running(true)
{
detect_thread = std::thread(&Detector::detect, this);
notify_thread = std::thread(&Detector::notify_handlers, this);
}
Detector::~Detector()
{
is_running = false;
detect_thread.join();
notify_thread.join();
}
void Detector::register_input_event_handler(InputEventHandler* handler)
{
std::lock_guard<std::mutex> event_handler_guard(event_handler_mutex);
event_handler.insert(handler);
}
void Detector::unregister_input_event_handler(InputEventHandler* handler)
{
std::lock_guard<std::mutex> event_handler_guard(event_handler_mutex);
event_handler.erase(handler);
}
void Detector::notify_handlers()
{
while(is_running)
{
// return if no event in queue
if(event_queue.empty())
{
std::this_thread::yield();
return;
}
InputEvent& event = event_queue.pop();
std::lock_guard<std::mutex> event_handler_guard(event_handler_mutex);
for(auto* handler : event_handler)
{
handler->handle(event);
}
}
}
void Detector::detect()
{
char address;
if(check_inputs(address))
while(is_running)
{
InputEvent& event = input_events.at(address);
notify_handlers(event);
}
}
void Detector::notify_handlers(InputEvent& event)
{
for(auto* handler : event_handler)
{
handler->handle(event);
char address;
if(check_inputs(address))
{
InputEvent& event = input_events.at(address);
event_queue.queue(event);
}
}
}