Skip to content

Commit

Permalink
Fix data race in aggregateLikelihood (#411)
Browse files Browse the repository at this point in the history
Fixes a data race in case of multi-threaded simulations.
nllh, objectiveFunctionGradient and simulationTimeSec are potentially updated by different threads at the same time.
  • Loading branch information
dweindl authored Nov 19, 2024
1 parent 57eddac commit d553b18
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/parpeamici/multiConditionProblem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include <cassert>
#include <cstring>
#include <ctime>
#include <mutex>
#include <numeric>
#include <utility>

Expand Down Expand Up @@ -719,6 +720,9 @@ int AmiciSummedGradientFunction::runSimulations(
std::vector<int> const& dataIndices, Logger *logger, double *cpuTime) const {

int errors = 0;
// Mutex to protect likelihood and gradient that are potentially updated
// by multiple threads
std::mutex mutex;

auto parameterVector = std::vector<double>(
optimizationParameters.begin(),
Expand All @@ -732,7 +736,10 @@ int AmiciSummedGradientFunction::runSimulations(
: amici::SensitivityOrder::none,
dataIndices,
[&nllh, &objectiveFunctionGradient, &simulationTimeSec,
&optimizationParameters, &errors, this](JobData *job, int /*jobIdx*/) {
&optimizationParameters, &errors, &mutex, this](JobData *job, int /*jobIdx*/) {
// protect shared variables llh, gradient, simulationTimeSec
std::lock_guard<std::mutex> lock(mutex);

errors += this->aggregateLikelihood(*job,
nllh,
objectiveFunctionGradient,
Expand Down

0 comments on commit d553b18

Please sign in to comment.