Skip to content

Commit

Permalink
Fix the race condition while calling rcl_shutdown (#1353)
Browse files Browse the repository at this point in the history
* Fix the race condition while calling rcl_shutdown

Signed-off-by: Barry Xu <[email protected]>

* Avoid calling rcl_shutdown() multiple times on the same context

Signed-off-by: Barry Xu <[email protected]>

* Multiple calls to Context::shutdown will throw an exception

Signed-off-by: Barry Xu <[email protected]>

* Update the name of an exception

Signed-off-by: Barry Xu <[email protected]>

---------

Signed-off-by: Barry Xu <[email protected]>
  • Loading branch information
Barry-Xu-2018 authored Nov 8, 2024
1 parent 53d7760 commit 34f9e13
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
21 changes: 11 additions & 10 deletions rclpy/src/rclpy/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -150,17 +150,18 @@ Context::ok()
void
Context::shutdown()
{
{
std::lock_guard<std::mutex> guard{g_contexts_mutex};
auto iter = std::find(g_contexts.begin(), g_contexts.end(), rcl_context_.get());
if (iter != g_contexts.end()) {
g_contexts.erase(iter);
}
std::lock_guard<std::mutex> guard{g_contexts_mutex};
if (already_shutdown_) {
throw ContextAlreadyShutdown("Context already shutdown.");
}

rcl_ret_t ret = rcl_shutdown(rcl_context_.get());
if (RCL_RET_OK != ret) {
throw RCLError("failed to shutdown");
auto iter = std::find(g_contexts.begin(), g_contexts.end(), rcl_context_.get());
if (iter != g_contexts.end()) {
g_contexts.erase(iter);
rcl_ret_t ret = rcl_shutdown(rcl_context_.get());
if (RCL_RET_OK != ret) {
throw RCLError("failed to shutdown");
}
already_shutdown_ = true;
}
}

Expand Down
1 change: 1 addition & 0 deletions rclpy/src/rclpy/context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class Context : public Destroyable, public std::enable_shared_from_this<Context>

private:
std::shared_ptr<rcl_context_t> rcl_context_;
bool already_shutdown_{false};
};

/// Define a pybind11 wrapper for an rclpy::Context
Expand Down
5 changes: 5 additions & 0 deletions rclpy/src/rclpy/exceptions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ class InvalidHandle : public std::runtime_error
using std::runtime_error::runtime_error;
};

class ContextAlreadyShutdown : public std::runtime_error
{
using std::runtime_error::runtime_error;
};

} // namespace rclpy

#endif // RCLPY__EXCEPTIONS_HPP_

0 comments on commit 34f9e13

Please sign in to comment.