Guard device adding and removing with mutex

It looks like Udev might retrigger device adding on
enumeration phase which causes addDevice() to be called
twice on the same device at the same time or too fast.

Adding a mutex to prevent this, so
DeviceManager::addDevice() is not
ran concurrently.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
This commit is contained in:
Seppo Takalo 2025-07-28 10:53:28 +03:00
parent 628ab937a2
commit fc68e7fc63
2 changed files with 8 additions and 3 deletions

View File

@ -157,10 +157,12 @@ void DeviceMonitor::_addHandler(const std::string& device, int tries) {
try {
auto supported_reports = backend::hidpp::getSupportedReports(
RawDevice::getReportDescriptor(device));
if (supported_reports)
if (supported_reports) {
std::lock_guard<std::mutex> lock(_devices_mutex);
addDevice(device);
else
} else {
logPrintf(DEBUG, "Unsupported device %s ignored", device.c_str());
}
} catch (backend::DeviceNotReady& e) {
if (tries == max_tries) {
logPrintf(WARN, "Failed to add device %s after %d tries. Treating as failure.",
@ -182,6 +184,7 @@ void DeviceMonitor::_addHandler(const std::string& device, int tries) {
void DeviceMonitor::_removeHandler(const std::string& device) {
try {
std::lock_guard<std::mutex> lock(_devices_mutex);
removeDevice(device);
} catch (std::exception& e) {
logPrintf(WARN, "Error removing device %s: %s",

View File

@ -95,6 +95,8 @@ namespace logid::backend::raw {
bool _ready;
std::weak_ptr<DeviceMonitor> _self;
mutable std::mutex _devices_mutex;
};
}