diff --git a/src/viam/sdk/robot/client.cpp b/src/viam/sdk/robot/client.cpp index 740c50fff..c4ad0c37f 100644 --- a/src/viam/sdk/robot/client.cpp +++ b/src/viam/sdk/robot/client.cpp @@ -143,7 +143,11 @@ RobotClient::~RobotClient() { } void RobotClient::close() { - should_refresh_.store(false); + if (should_refresh_) { + const std::unique_lock lk{refresh_lock_}; + should_refresh_ = false; + refresh_cv_.notify_one(); + } if (refresh_thread_.joinable()) { refresh_thread_.join(); @@ -220,16 +224,22 @@ void RobotClient::refresh() { } void RobotClient::refresh_every() { - while (should_refresh_.load()) { - try { - std::this_thread::sleep_for(refresh_interval_); - refresh(); + std::unique_lock lk{refresh_lock_}; - } catch (std::exception&) { - break; + refresh_cv_.wait_for(lk, refresh_interval_, [this] { + if (should_refresh_) { + try { + refresh(); + } catch (const std::exception& e) { + VIAM_SDK_LOG(warn) << "Refresh thread got exception " << e.what(); + // TODO: maybe recoverable + return true; + } } - } -}; + + return !should_refresh_; + }); +} RobotClient::RobotClient(ViamChannel channel) : viam_channel_(std::move(channel)), diff --git a/src/viam/sdk/robot/client.hpp b/src/viam/sdk/robot/client.hpp index 3c19a9edc..6e6a36112 100644 --- a/src/viam/sdk/robot/client.hpp +++ b/src/viam/sdk/robot/client.hpp @@ -3,7 +3,7 @@ /// @brief gRPC client implementation for a `robot`. #pragma once -#include +#include #include #include @@ -186,7 +186,9 @@ class RobotClient { void refresh_every(); std::thread refresh_thread_; - std::atomic should_refresh_; + std::mutex refresh_lock_; + std::condition_variable refresh_cv_; + bool should_refresh_; std::chrono::seconds refresh_interval_; ViamChannel viam_channel_;