diff --git a/pybamm/solvers/base_solver.py b/pybamm/solvers/base_solver.py index 28dd4bdd9d..0e60aca189 100644 --- a/pybamm/solvers/base_solver.py +++ b/pybamm/solvers/base_solver.py @@ -13,10 +13,6 @@ import pybamm from pybamm.expression_tree.binary_operators import _Heaviside -# Set context for parallel processing depending on the platform -if platform.system() == "Darwin" or platform.system() == "Linux": - mp.set_start_method("fork") - class BaseSolver: """Solve a discretised model. @@ -70,6 +66,7 @@ def __init__( self.algebraic_solver = False self._on_extrapolation = "warn" self.computed_var_fcns = {} + self._mp_context = self.get_platform_context(platform.system()) @property def root_method(self): @@ -917,7 +914,7 @@ def solve( model_inputs_list, ) else: - with mp.Pool(processes=nproc) as p: + with mp.get_context(self._mp_context).Pool(processes=nproc) as p: new_solutions = p.starmap( self._integrate, zip( @@ -1395,6 +1392,12 @@ def check_extrapolation(self, solution, events): "outside these bounds." ) + def get_platform_context(self, system_type: str): + # Set context for parallel processing depending on the platform + if system_type.lower() in ["linux", "darwin"]: + return "fork" + return "spawn" + @staticmethod def _set_up_model_inputs(model, inputs): """Set up input parameters""" diff --git a/tests/unit/test_solvers/test_base_solver.py b/tests/unit/test_solvers/test_base_solver.py index dcd4b5b856..9a6dec0eaf 100644 --- a/tests/unit/test_solvers/test_base_solver.py +++ b/tests/unit/test_solvers/test_base_solver.py @@ -348,6 +348,12 @@ def test_multiple_models_error(self): with self.assertRaisesRegex(RuntimeError, "already been initialised"): solver.solve(model2, t_eval=[0, 1]) + def test_multiprocess_context(self): + solver = pybamm.BaseSolver() + assert solver.get_platform_context("Win") == "spawn" + assert solver.get_platform_context("Linux") == "fork" + assert solver.get_platform_context("Darwin") == "fork" + @unittest.skipIf(not pybamm.have_idaklu(), "idaklu solver is not installed") def test_sensitivities(self): def exact_diff_a(y, a, b):