DevReattacher: Spinlock-protect stop() call

Replace the current delay timeout mechanism with a spinlock.
Both mechanisms try to eliminate the possibility of an in-flight
async op accessing state that has been destroyed by stop().

But the spinlock is less arbitrary.
This commit is contained in:
2025-11-27 22:52:09 -04:00
parent 1e76d51c41
commit 2a8d320f7a
2 changed files with 12 additions and 24 deletions
+8 -22
View File
@@ -3,7 +3,6 @@
#include <functional> #include <functional>
#include <componentThread.h> #include <componentThread.h>
#include <callback.h> #include <callback.h>
#include <asynchronousBridge.h>
#include <deviceManager/deviceReattacher.h> #include <deviceManager/deviceReattacher.h>
#include <deviceManager/deviceManager.h> #include <deviceManager/deviceManager.h>
@@ -28,37 +27,23 @@ timer(ioThread->getIoService())
void DeviceReattacher::start() void DeviceReattacher::start()
{ {
shouldContinue.store(true); shouldContinue = true;
scheduleNextTimeout(); scheduleNextTimeout();
} }
void DeviceReattacher::stop() void DeviceReattacher::stop()
{ {
shouldContinue.store(false);
timer.cancel();
// Set up a timeout bridge using the provided ioThread's io_service
auto& ioService = ioThread->getIoService();
boost::asio::deadline_timer timeoutTimer(ioService);
AsynchronousBridge bridge(ioService);
// Set up the timeout for ~10ms
timeoutTimer.expires_from_now(boost::posix_time::milliseconds(20));
timeoutTimer.async_wait(
[&bridge](const boost::system::error_code& error)
{ {
(void)error; SpinLock::Guard lock(shouldContinueLock);
shouldContinue = false;
}
// Always signal complete, whether timeout expired or was cancelled timer.cancel();
bridge.setAsyncOperationComplete();
});
bridge.waitForAsyncOperationCompleteOrIoServiceStopped();
} }
void DeviceReattacher::scheduleNextTimeout() void DeviceReattacher::scheduleNextTimeout()
{ {
if (!shouldContinue.load()) { if (!shouldContinue) {
return; return;
} }
@@ -85,7 +70,8 @@ void DeviceReattacher::onTimeout(const boost::system::error_code& error)
return; return;
} }
if (!shouldContinue.load()) { SpinLock::Guard lock(shouldContinueLock);
if (!shouldContinue) {
return; return;
} }
@@ -5,6 +5,7 @@
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <boost/asio/deadline_timer.hpp> #include <boost/asio/deadline_timer.hpp>
#include <spinLock.h>
namespace smo { namespace smo {
@@ -35,7 +36,8 @@ private:
DeviceManager &parent; DeviceManager &parent;
std::shared_ptr<ComponentThread> ioThread; std::shared_ptr<ComponentThread> ioThread;
std::atomic<bool> shouldContinue; SpinLock shouldContinueLock;
bool shouldContinue;
boost::asio::deadline_timer timer; boost::asio::deadline_timer timer;
}; };