From af2ce73e38648bcc9010625ceef517b35a747b7a Mon Sep 17 00:00:00 2001
From: Christoph Lehmann <christoph.lehmann@ufz.de>
Date: Fri, 14 Apr 2023 12:20:59 +0200
Subject: [PATCH] [MPL] Made function property thread safe

---
 MaterialLib/MPL/Properties/Function.cpp | 20 +++++++++++++-------
 MaterialLib/MPL/Properties/Function.h   |  2 ++
 2 files changed, 15 insertions(+), 7 deletions(-)

diff --git a/MaterialLib/MPL/Properties/Function.cpp b/MaterialLib/MPL/Properties/Function.cpp
index 65897c1c11c..2c256f7935c 100644
--- a/MaterialLib/MPL/Properties/Function.cpp
+++ b/MaterialLib/MPL/Properties/Function.cpp
@@ -77,13 +77,18 @@ static void updateVariableValues(
 static PropertyDataType evaluateExpressions(
     std::vector<std::pair<Variable, double*>> const& symbol_values,
     VariableArray const& variable_array,
-    std::vector<exprtk::expression<double>> const& expressions)
+    std::vector<exprtk::expression<double>> const& expressions,
+    std::mutex& mutex)
 {
-    updateVariableValues(symbol_values, variable_array);
-
     std::vector<double> result(expressions.size());
-    std::transform(begin(expressions), end(expressions), begin(result),
-                   [](auto const& e) { return e.value(); });
+
+    {
+        std::lock_guard lock_guard(mutex);
+        updateVariableValues(symbol_values, variable_array);
+
+        std::transform(begin(expressions), end(expressions), begin(result),
+                       [](auto const& e) { return e.value(); });
+    }
 
     switch (result.size())
     {
@@ -187,7 +192,7 @@ PropertyDataType Function::value(VariableArray const& variable_array,
                                  double const /*t*/, double const /*dt*/) const
 {
     return evaluateExpressions(symbol_values_, variable_array,
-                               value_expressions_);
+                               value_expressions_, mutex_);
 }
 
 PropertyDataType Function::dValue(VariableArray const& variable_array,
@@ -208,7 +213,8 @@ PropertyDataType Function::dValue(VariableArray const& variable_array,
             variable_enum_to_string[static_cast<int>(variable)], name_);
     }
 
-    return evaluateExpressions(symbol_values_, variable_array, it->second);
+    return evaluateExpressions(symbol_values_, variable_array, it->second,
+                               mutex_);
 }
 
 }  // namespace MaterialPropertyLib
diff --git a/MaterialLib/MPL/Properties/Function.h b/MaterialLib/MPL/Properties/Function.h
index 49263d67987..f7ec49e35be 100644
--- a/MaterialLib/MPL/Properties/Function.h
+++ b/MaterialLib/MPL/Properties/Function.h
@@ -55,5 +55,7 @@ private:
     /// Multiple expressions are representing vector-valued functions.
     std::vector<std::pair<Variable, std::vector<Expression>>>
         dvalue_expressions_;
+
+    mutable std::mutex mutex_;
 };
 }  // namespace MaterialPropertyLib
-- 
GitLab