Skip to content

Commit ef2ee1e

Browse files
authored
Merge pull request #499 from The-Strategy-Unit/multiprocessing_spawn
switches to using spawn multiprocessing
2 parents 4f50474 + 81fc432 commit ef2ee1e

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/nhp/model/run.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""Run the model."""
22

33
import logging
4+
import multiprocessing
45
import os
56
import time
6-
from multiprocessing import Pool
77
from typing import Any, Callable, Tuple, Type
88

99
from tqdm.auto import tqdm as base_tqdm
@@ -84,7 +84,8 @@ def _run_model(
8484
cpus = os.cpu_count()
8585
batch_size = int(os.getenv("BATCH_SIZE", "1"))
8686

87-
with Pool(cpus) as pool:
87+
ctx = multiprocessing.get_context("spawn")
88+
with ctx.Pool(cpus) as pool:
8889
baseline = model.go(0) # baseline
8990
model_results: list[ModelRunResult] = list(
9091
tqdm(

tests/unit/nhp/model/test_run.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,16 @@ def test_run_model(mocker):
5151
params = {"start_year": 2020, "end_year": 2022, "model_runs": 2}
5252
mocker.patch("os.cpu_count", return_value=2)
5353

54-
pool_mock = mocker.patch("nhp.model.run.Pool")
54+
pool_ctx_mock = mocker.patch("multiprocessing.get_context")
55+
pool_mock = pool_ctx_mock().Pool
5556
pool_ctm = pool_mock.return_value.__enter__.return_value
5657
pool_ctm.name = "pool"
5758
pool_ctm.imap = Mock(wraps=lambda f, i, **kwargs: map(f, i))
5859

5960
pc_m = Mock()
6061

62+
pool_ctx_mock.reset_mock()
63+
6164
# act
6265
actual = _run_model(model_m, params, "data", "hsa", "run_params", pc_m, False) # type: ignore
6366

@@ -66,6 +69,9 @@ def test_run_model(mocker):
6669
assert actual == [model_m().go()] * 3
6770
pc_m.assert_called_once_with(2)
6871

72+
pool_ctx_mock.assert_called_once_with("spawn")
73+
pool_mock.assert_called_once_with(2)
74+
6975

7076
def test_noop_progress_callback():
7177
# arrange, act & assert

0 commit comments

Comments
 (0)