Skip to content

Commit 05b21d8

Browse files
committed
condition var refresh thread
1 parent 565cf4c commit 05b21d8

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

src/viam/sdk/robot/client.cpp

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,11 @@ RobotClient::~RobotClient() {
143143
}
144144

145145
void RobotClient::close() {
146-
should_refresh_.store(false);
146+
if (should_refresh_) {
147+
std::unique_lock<std::mutex> lk{refresh_lock_};
148+
should_refresh_ = false;
149+
refresh_cv_.notify_one();
150+
}
147151

148152
if (refresh_thread_.joinable()) {
149153
refresh_thread_.join();
@@ -220,16 +224,21 @@ void RobotClient::refresh() {
220224
}
221225

222226
void RobotClient::refresh_every() {
223-
while (should_refresh_.load()) {
224-
try {
225-
std::this_thread::sleep_for(refresh_interval_);
226-
refresh();
227+
std::unique_lock<std::mutex> lk{refresh_lock_};
227228

228-
} catch (std::exception&) {
229+
while (true) {
230+
if (refresh_cv_.wait_for(lk, refresh_interval_) == std::cv_status::timeout) {
231+
try {
232+
refresh();
233+
} catch (const std::exception& e) {
234+
VIAM_SDK_LOG(warn) << "Refresh thread terminated with exception: " << e.what();
235+
break;
236+
}
237+
} else if (should_refresh_ == false) {
229238
break;
230239
}
231240
}
232-
};
241+
}
233242

234243
RobotClient::RobotClient(ViamChannel channel)
235244
: viam_channel_(std::move(channel)),

src/viam/sdk/robot/client.hpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ class RobotClient {
186186
void refresh_every();
187187

188188
std::thread refresh_thread_;
189-
std::atomic<bool> should_refresh_;
189+
std::mutex refresh_lock_;
190+
std::condition_variable refresh_cv_;
191+
bool should_refresh_;
190192
std::chrono::seconds refresh_interval_;
191193

192194
ViamChannel viam_channel_;

0 commit comments

Comments
 (0)