[ROS2] Close all threads when using CTRL-C
Hi all! In my project I'm spawning a thread which contains a while loop, simply like so:
std::thread worker([this]() { this->ballotCheckingThread(); });
std::unique_lock<std::mutex> lock(this->candidate_mutex_);
where the thread code is like this
void ballotCheckingThread() {
while (!this->checkVotingCompleted() && !this->checkForExternalLeader()) {
// Simulate some delay between checks
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
// Notify the first thread to stop waiting
cv.notify_all();
}
Unfortunately, when I use CTRL-C to terminate the node, this thread remains hanging and I have to manually kill it.
Right now in the main function I'm doing this:
int main(int argc, char *argv[]) {
std::cout << "Starting node..." << std::endl;
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
rclcpp::init(argc, argv);
rclcpp::Node::SharedPtr node = std::make_shared<myNode>();
rclcpp::executors::MultiThreadedExecutor executor;
executor.add_node(node);
try {
executor.spin();
} catch (std::exception& e) {
std::cout << "rclcpp shutting down..." << std::endl;
rclcpp::shutdown();
return 0;
}
}
but I guess that's not enough. Is there a standard way to do this?