ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange |
1 | initial version |
You have to really think about what resource your mutex is protecting, it was not clear what your intention is. I guess you have some protected process that you want to start/stop. In that case, it would look something like this:
Called from a thread A:
tm = nh.createTimer(ros::Duration(...), MyClass::timerCallback);
Called from a thread B:
my_mutex.lock();
// at this point, we are guaranteed that no protected process is running, but a timerCallback could be blocked
if (some_condition) {
need_to_process = false
my_mutex.unlock();
// don't lock around timer because it has an internal mutex
tm.stop(); // wait for finishing of the timerCallback
// at this point in the code, the timer is timerCallback not running anymore
}
my_mutex.unlock();
Called from a thread C:
void MyClass::timerCallback(ros::TimerEvent ev) {
std::lock_guard<std::mutex> lock(my_mutex);
if (need_to_process)
// protected process ...
}
2 | No.2 Revision |
You have to really think about what resource your mutex is protecting, it was not clear what your intention is. I guess you have some protected process that you want to start/stop. In that case, it would look something like this:
Called from a thread A:
tm = nh.createTimer(ros::Duration(...), MyClass::timerCallback);
Called from a thread B:
my_mutex.lock();
// at this point, we are guaranteed that no protected process is running, but a timerCallback could be blocked
if (some_condition) {
need_to_process = false
my_mutex.unlock();
// don't lock around timer because it has an internal mutex
tm.stop(); // wait for finishing of the timerCallback
// at this point in the code, the timer is timerCallback not running anymore
} else {
my_mutex.unlock();
}
my_mutex.unlock();
Called from a thread C:
void MyClass::timerCallback(ros::TimerEvent ev) {
std::lock_guard<std::mutex> lock(my_mutex);
if (need_to_process)
// protected process ...
}