Skip to content

RSDK-10643: condition var refresh thread #428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions src/viam/sdk/robot/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,11 @@ RobotClient::~RobotClient() {
}

void RobotClient::close() {
should_refresh_.store(false);
if (should_refresh_) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If should_refresh_ is changing state, it should do so under the lock I think.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is not changing state-- should_refresh_ is only mutated in this method and in the named constructor which sets it in the first place, so there may be a concurrent read happening here but there's no way for it to be read while being mutated

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll argue that this is one of those cases where even if it is safe in practice, it is still better to do the check under the lock. It'll be annoying if someday we stand up TSAN and it whines about a leak here, and this isn't a hot path, so trying to eliminate the lock doesn't buy much of anything.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean race of course, not leak, since I'm talking about TSAN not ASAN.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd even move the read of should_referesh_ under the lock, or even eliminate the check entirely. It should be fine in close to just unconditionally set should_refresh_ = false (under the lock), and then notify. If there is no refresh thread, it is just a big no-op.

const std::unique_lock<std::mutex> lk{refresh_lock_};
should_refresh_ = false;
refresh_cv_.notify_one();
}

if (refresh_thread_.joinable()) {
refresh_thread_.join();
Expand Down Expand Up @@ -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<std::mutex> lk{refresh_lock_};

} catch (std::exception&) {
break;
refresh_cv_.wait_for(lk, refresh_interval_, [this] {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is going to terminate after one timeout, but tbh I always get this stuff wrong, so don't let me mislead you if you have thought it through and this actually does what is intended.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you were right, classic case of a solution that is simple, elegant, and wrong 🙂

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm generally skeptical of the predicate taking condition things because they are so easy to get wrong, and require too much thinking.

Here is how I think I would write this loop unrolled:

std::unique_lock<std::mutex> lk{refresh_lock_};
// Terminate if we ever see `should_refresh` as `false` while holding the lock
while (should_refresh_) {
    // Compute the absolute time on which the next refresh should happen
    const auto wake_time = std::chrono::steady_clock::now + refresh_interval_;
    // Loop until deadline is reached or `should_refresh_` becomes `false`
    while (should_refresh_) {
        const auto wait_result = refresh_cv.wait_until(lk, wake_time);
        if (wait_result == cv_status::timeout && should_refresh_) {
            // We hit the deadline: do a refresh
            try {
                refresh();
            } catch (...) { ... }
            // Break out of inner loop to compute next deadline
            break;
        } else {
            // If this was a spurious wake, then `should_refresh_` is still `true`, and
            // `wait_until` will be reinvoked with existing deadline. If this was not
            // a spurious wake, then we were notified, and both the inner and outer loop
            // will terminate.
        }
    }
}

But it is possible that the predicate version is more or less equivalent to that, in which case it should be fine.

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)),
Expand Down
6 changes: 4 additions & 2 deletions src/viam/sdk/robot/client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/// @brief gRPC client implementation for a `robot`.
#pragma once

#include <atomic>
#include <condition_variable>
#include <string>
#include <thread>

Expand Down Expand Up @@ -186,7 +186,9 @@ class RobotClient {
void refresh_every();

std::thread refresh_thread_;
std::atomic<bool> should_refresh_;
std::mutex refresh_lock_;
std::condition_variable refresh_cv_;
bool should_refresh_;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be possible to eliminate the bool by making refresh_interval_ an optional.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think you're right, we're storing a T data; bool valid; which is basically just what an optional is under the hood.

(we could just have refresh_interval_ alone do all the work, but it's a little less self-documenting, although there are compact_optional types that allow this sort of thing)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is probably worth doing. There's just less state to manage, which means less risk of things decohering. It'd also simplify RobotClient::with_channel:

From

    robot->refresh_interval_ = std::chrono::seconds{options.refresh_interval()};
    robot->should_refresh_ = (robot->refresh_interval_ > std::chrono::seconds{0});
    if (robot->should_refresh_) {
        robot->refresh_thread_ = std::thread{&RobotClient::refresh_every, robot.get()};
    }

To

    if (options.refresh_interval() != 0) {
        robot->refresh_interval_.reset(options.refresh_interval());
        robot->refresh_thread_ = std::thread{&RobotClient::refresh_every, robot.get()}
    }

std::chrono::seconds refresh_interval_;

ViamChannel viam_channel_;
Expand Down