Skip to content

Commit 9ddb1ae

Browse files
committed
Destroy subscription when not needed, avoid re-creating it
1 parent ac4132b commit 9ddb1ae

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

rclcpp/include/rclcpp/time_source.hpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,17 @@ class TimeSource
8080
using Alloc = std::allocator<void>;
8181
using SubscriptionT = rclcpp::Subscription<MessageT, Alloc>;
8282
std::shared_ptr<SubscriptionT> clock_subscription_;
83+
std::mutex clock_sub_lock_;
8384

8485
// The clock callback itself
8586
void clock_cb(const rosgraph_msgs::msg::Clock::SharedPtr msg);
8687

8788
// Create the subscription for the clock topic
8889
void create_clock_sub();
8990

91+
// Destroy the subscription for the clock topic
92+
void destroy_clock_sub();
93+
9094
// Parameter Client pointer
9195
std::shared_ptr<rclcpp::AsyncParametersClient> parameter_client_;
9296

rclcpp/src/rclcpp/time_source.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ TimeSource::TimeSource(std::shared_ptr<rclcpp::Node> node)
3737
: ros_time_active_(false)
3838
{
3939
this->attachNode(node);
40+
clock_subscription_.reset();
4041
}
4142

4243
TimeSource::TimeSource()
@@ -158,6 +159,11 @@ void TimeSource::clock_cb(const rosgraph_msgs::msg::Clock::SharedPtr msg)
158159

159160
void TimeSource::create_clock_sub()
160161
{
162+
std::lock_guard<std::mutex> guard(clock_sub_lock_);
163+
if (clock_subscription_) {
164+
// Subscription already created.
165+
return;
166+
}
161167
const std::string topic_name = "/clock";
162168

163169
rclcpp::callback_group::CallbackGroup::SharedPtr group;
@@ -180,6 +186,16 @@ void TimeSource::create_clock_sub()
180186
allocator);
181187
}
182188

189+
void TimeSource::destroy_clock_sub()
190+
{
191+
std::lock_guard<std::mutex> guard(clock_sub_lock_);
192+
if (!clock_subscription_) {
193+
// Subscription already destroyed/never created.
194+
return;
195+
}
196+
clock_subscription_.reset();
197+
}
198+
183199
void TimeSource::on_parameter_event(const rcl_interfaces::msg::ParameterEvent::SharedPtr event)
184200
{
185201
// Filter for only 'use_sim_time' being added or changed.
@@ -198,6 +214,7 @@ void TimeSource::on_parameter_event(const rcl_interfaces::msg::ParameterEvent::S
198214
} else {
199215
parameter_state_ = SET_FALSE;
200216
disable_ros_time();
217+
destroy_clock_sub();
201218
}
202219
}
203220
// Handle the case that use_sim_time was deleted.

0 commit comments

Comments
 (0)