Skip to content

Commit cd9099d

Browse files
authored
Reapply "Catch the exception from rate.sleep() if the context is invalid. (#2956)" (#2963) (#2964)
This reverts commit 6fbf039. Signed-off-by: Tomoya Fujita <[email protected]>
1 parent 6fbf039 commit cd9099d

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

rclcpp/src/rclcpp/rate.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,13 @@ Rate::sleep()
6767
// Calculate the time to sleep
6868
auto time_to_sleep = next_interval - now;
6969
// Sleep (will get interrupted by ctrl-c, may not sleep full time)
70-
clock_->sleep_for(time_to_sleep);
70+
try {
71+
// If the context is invalid, an exception will be thrown.
72+
clock_->sleep_for(time_to_sleep);
73+
} catch (const std::runtime_error & e) {
74+
// If it didn't sleep the full time, return false
75+
return false;
76+
}
7177
return true;
7278
}
7379

rclcpp/test/rclcpp/test_rate.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,12 @@ TEST_F(TestRate, incorrect_constuctor) {
173173
rclcpp::Rate rate(rclcpp::Duration(-1, 0)),
174174
std::invalid_argument("period must be greater than 0"));
175175
}
176+
177+
TEST(TestRateBasic, invalid_context) {
178+
rclcpp::init(0, nullptr);
179+
rclcpp::Rate rate(1.0);
180+
ASSERT_TRUE(rate.sleep());
181+
rclcpp::shutdown();
182+
EXPECT_NO_THROW(rate.sleep());
183+
ASSERT_FALSE(rate.sleep());
184+
}

0 commit comments

Comments
 (0)