Skip to content

Commit

Permalink
Fix race conditions in froot and Solver::timeExceeded
Browse files Browse the repository at this point in the history
Static variables should have been declared thread-local, but haven't.

* Fixes race conditions in froot, which could have resulted in incorrect simulation results for models with events/heavisides/piecewise, for multi-threaded simulations.

* Fixes race conditions for the max-time check, which could have resulted in incorrect termination of simulations in case of multi-threaded simulations in combination with a time limit.
  • Loading branch information
dweindl committed Nov 19, 2024
1 parent 022de60 commit cd46620
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/solver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,7 @@ void Solver::setMaxTime(double maxtime) {
void Solver::startTimer() const { simulation_timer_.reset(); }

bool Solver::timeExceeded(int interval) const {
static int eval_counter = 0;
thread_local static int eval_counter = 0;

// 0 means infinite time
if (maxtime_.count() == 0)
Expand Down
3 changes: 2 additions & 1 deletion src/solver_cvodes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,8 @@ static int froot(realtype t, N_Vector x, realtype* root, void* user_data) {
if (model->ne != model->ne_solver) {
// temporary buffer to store all root function values, not only the ones
// tracked by the solver
static std::vector<realtype> root_buffer(model->ne, 0.0);
thread_local static std::vector<realtype> root_buffer(model->ne, 0.0);
root_buffer.resize(model->ne);
model->froot(t, x, root_buffer);
std::copy_n(root_buffer.begin(), model->ne_solver, root);
} else {
Expand Down

0 comments on commit cd46620

Please sign in to comment.