threading again
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user