Skip to content

Commit 78aefea

Browse files
committed
fix: set multiprocessing context according to OS
1 parent bec29f2 commit 78aefea

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

neo4j-app/neo4j_app/app/dependencies.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import multiprocessing
55
import os
6+
import platform
67
import sys
78
import tempfile
89
import traceback
@@ -37,6 +38,7 @@
3738
_TEST_DB_FILE: Optional[Path] = None
3839
_TEST_LOCK: Optional[multiprocessing.Lock] = None
3940
_PROCESS_EXECUTOR: Optional[concurrent.futures.ProcessPoolExecutor] = None
41+
_MP_CONTEXT = None
4042

4143

4244
class DependencyInjectionError(RuntimeError):
@@ -63,6 +65,24 @@ def lifespan_config() -> AppConfig:
6365
return cast(AppConfig, _CONFIG)
6466

6567

68+
def mp_context_enter(**__):
69+
global _MP_CONTEXT
70+
platform_system = platform.system()
71+
if platform_system == "Darwin":
72+
ctx = "spawn"
73+
elif platform_system == "Linux":
74+
ctx = "fork"
75+
else:
76+
raise ValueError(f"Unsupported OS: {platform_system}")
77+
_MP_CONTEXT = multiprocessing.get_context(ctx)
78+
79+
80+
def lifespan_mp_context():
81+
if _MP_CONTEXT is None:
82+
raise DependencyInjectionError("multiprocessing context")
83+
return _MP_CONTEXT
84+
85+
6686
async def neo4j_driver_enter(**__):
6787
global _NEO4J_DRIVER
6888
_NEO4J_DRIVER = lifespan_config().to_neo4j_driver()
@@ -164,7 +184,7 @@ def process_executor_enter(**_):
164184
worker_ids = [f"worker-{process_id}-{i}" for i in range(n_workers)]
165185
_PROCESS_EXECUTOR = concurrent.futures.ProcessPoolExecutor( # pylint: disable=unnecessary-dunder-call
166186
max_workers=n_workers,
167-
mp_context=multiprocessing.get_context("spawn"),
187+
mp_context=lifespan_mp_context(),
168188
).__enter__()
169189
kwargs = dict()
170190
worker_cls = config.to_worker_cls()
@@ -261,6 +281,7 @@ def lifespan_event_publisher() -> EventPublisher:
261281
("neo4j driver creation", neo4j_driver_enter, neo4j_driver_exit),
262282
("neo4j project registry creation", create_project_registry_db_enter, None),
263283
("ES client creation", es_client_enter, es_client_exit),
284+
(None, mp_context_enter, None),
264285
(None, test_process_manager_enter, test_process_manager_exit),
265286
(None, test_db_path_enter, test_db_path_exit),
266287
(None, _test_lock_enter, None),

0 commit comments

Comments
 (0)