Gradient checker multithreading bugfix. This is a follow-up on c/7470. GradientCheckingCostFunction calls callback_->SetGradientErrorDetected() in its Evaluate method, which will run in multiple threads simultaneously when enabling this option in the solver. Thus, the string append operation inside that method has to be protected by a mutex. Change-Id: I314ef1df2be52595370d9af05851bf6da39bb45e
diff --git a/internal/ceres/gradient_checking_cost_function.cc b/internal/ceres/gradient_checking_cost_function.cc index 6f0c59b..f2c7336 100644 --- a/internal/ceres/gradient_checking_cost_function.cc +++ b/internal/ceres/gradient_checking_cost_function.cc
@@ -148,8 +148,10 @@ } void GradientCheckingIterationCallback::SetGradientErrorDetected( std::string& error_log) { + mutex_.Lock(); gradient_error_detected_ = true; error_log_ += "\n" + error_log; + mutex_.Unlock(); } CostFunction* CreateGradientCheckingCostFunction(
diff --git a/internal/ceres/gradient_checking_cost_function.h b/internal/ceres/gradient_checking_cost_function.h index d8bbfed..f137349 100644 --- a/internal/ceres/gradient_checking_cost_function.h +++ b/internal/ceres/gradient_checking_cost_function.h
@@ -37,6 +37,7 @@ #include "ceres/cost_function.h" #include "ceres/iteration_callback.h" #include "ceres/local_parameterization.h" +#include "ceres/mutex.h" namespace ceres { namespace internal { @@ -53,14 +54,17 @@ // then return SOLVER_ABORT. virtual CallbackReturnType operator()(const IterationSummary& summary); - // Notify this that a gradient error has occured. + // Notify this that a gradient error has occured (thread safe). void SetGradientErrorDetected(std::string& error_log); + // Retrieve error status (not thread safe). bool gradient_error_detected() const { return gradient_error_detected_; } const std::string& error_log() const { return error_log_; } private: bool gradient_error_detected_; std::string error_log_; + // Mutex protecting member variables. + ceres::internal::Mutex mutex_; }; // Creates a CostFunction that checks the Jacobians that cost_function computes