From 7803c55a885f24ec3a256f3a99f829b409f97def Mon Sep 17 00:00:00 2001 From: Kai Bao Date: Mon, 5 Aug 2024 11:46:28 +0200 Subject: [PATCH] avoiding exception from std::stoi("") when not setting OMP_NUM_THREADS in the environment. --- opm/simulators/flow/Main.hpp | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/opm/simulators/flow/Main.hpp b/opm/simulators/flow/Main.hpp index 45ba34c31..991320833 100644 --- a/opm/simulators/flow/Main.hpp +++ b/opm/simulators/flow/Main.hpp @@ -711,23 +711,33 @@ private: #ifdef _OPENMP // This function is called before the parallel OpenMP stuff gets initialized. - // That initialization happends after the deck is read and we want this message. + // That initialization happens after the deck is read and we want this message. // Hence we duplicate the code of setupParallelism to get the number of threads. static bool first_time = true; const int default_threads = 2; const int requested_threads = Parameters::get(); + threads = requested_threads > 0 ? requested_threads : default_threads; + const char* env_var = getenv("OMP_NUM_THREADS"); int omp_num_threads = -1; try { - omp_num_threads = std::stoi(env_var ? env_var : ""); - if (first_time && requested_threads > 0 && FlowGenericVanguard::comm().rank()==0) { - std::cout << "Warning: Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument." << std::endl; + if (env_var) { + omp_num_threads = std::stoi(env_var); } - } catch (const std::invalid_argument& e) { - omp_num_threads = requested_threads > 0 ? requested_threads : default_threads; + } catch (const std::invalid_argument&) { + // Do nothing if an invalid_argument exception is caught } - threads = omp_num_threads; - first_time = false; + + // Set threads to omp_num_threads if it was successfully parsed and is positive + if (omp_num_threads > 0) { + if (first_time && FlowGenericVanguard::comm().rank() == 0 && requested_threads > 0) { + std::cout << "Warning: Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument." + << std::endl; + } + threads = omp_num_threads; + } + + first_time = false; #else threads = 1; #endif