|
19 | 19 | import asyncio |
20 | 20 | import os |
21 | 21 | import time |
| 22 | +import atexit |
22 | 23 | from .user_app_loader import load_user_app |
23 | 24 | from .runtime import execution_context |
24 | 25 | import logging |
|
31 | 32 | # --------------------------------------------- |
32 | 33 | _pool_lock = threading.Lock() |
33 | 34 | _pool: ProcessPoolExecutor | None = None |
| 35 | +_pool_cleanup_registered = False |
34 | 36 | _user_apps: list[str] = [] |
35 | 37 | _logger = logging.getLogger(__name__) |
36 | 38 |
|
37 | 39 |
|
| 40 | +def shutdown_pool_at_exit() -> None: |
| 41 | + """Best-effort shutdown of the global ProcessPoolExecutor on interpreter exit.""" |
| 42 | + global _pool, _pool_cleanup_registered # pylint: disable=global-statement |
| 43 | + with _pool_lock: |
| 44 | + if _pool is not None: |
| 45 | + try: |
| 46 | + _pool.shutdown(wait=True, cancel_futures=True) |
| 47 | + except Exception as e: |
| 48 | + _logger.error( |
| 49 | + "Error during ProcessPoolExecutor shutdown at exit: %s", |
| 50 | + e, |
| 51 | + exc_info=True, |
| 52 | + ) |
| 53 | + finally: |
| 54 | + _pool = None |
| 55 | + _pool_cleanup_registered = False |
| 56 | + |
| 57 | + |
38 | 58 | def _get_pool() -> ProcessPoolExecutor: |
39 | | - global _pool |
| 59 | + global _pool, _pool_cleanup_registered # pylint: disable=global-statement |
40 | 60 | with _pool_lock: |
41 | 61 | if _pool is None: |
| 62 | + if not _pool_cleanup_registered: |
| 63 | + # Register the shutdown at exit at creation time (rather than at import time) |
| 64 | + # to make sure it's executed earlier in the shutdown sequence. |
| 65 | + atexit.register(shutdown_pool_at_exit) |
| 66 | + _pool_cleanup_registered = True |
| 67 | + |
42 | 68 | # Single worker process as requested |
43 | 69 | _pool = ProcessPoolExecutor( |
44 | 70 | max_workers=1, |
@@ -213,11 +239,9 @@ def _sp_call(key_bytes: bytes, args: tuple[Any, ...], kwargs: dict[str, Any]) -> |
213 | 239 |
|
214 | 240 |
|
215 | 241 | class _ExecutorStub: |
216 | | - _pool: ProcessPoolExecutor |
217 | 242 | _key_bytes: bytes |
218 | 243 |
|
219 | 244 | def __init__(self, executor_factory: type[Any], spec: Any) -> None: |
220 | | - self._pool = _get_pool() |
221 | 245 | self._key_bytes = pickle.dumps( |
222 | 246 | (executor_factory, spec), protocol=pickle.HIGHEST_PROTOCOL |
223 | 247 | ) |
|
0 commit comments