|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: BSD-2-Clause |
| 3 | + |
| 4 | +import threading |
| 5 | +import functools |
| 6 | +import numba.cuda.core.event as ev |
| 7 | + |
| 8 | + |
| 9 | +# Lock for the preventing multiple compiler execution |
| 10 | +class _CompilerLock(object): |
| 11 | + def __init__(self): |
| 12 | + self._lock = threading.RLock() |
| 13 | + |
| 14 | + def acquire(self): |
| 15 | + ev.start_event("numba.cuda:compiler_lock") |
| 16 | + self._lock.acquire() |
| 17 | + |
| 18 | + def release(self): |
| 19 | + self._lock.release() |
| 20 | + ev.end_event("numba.cuda:compiler_lock") |
| 21 | + |
| 22 | + def __enter__(self): |
| 23 | + self.acquire() |
| 24 | + |
| 25 | + def __exit__(self, exc_val, exc_type, traceback): |
| 26 | + self.release() |
| 27 | + |
| 28 | + def is_locked(self): |
| 29 | + is_owned = getattr(self._lock, "_is_owned") |
| 30 | + if not callable(is_owned): |
| 31 | + is_owned = self._is_owned |
| 32 | + return is_owned() |
| 33 | + |
| 34 | + def __call__(self, func): |
| 35 | + @functools.wraps(func) |
| 36 | + def _acquire_compile_lock(*args, **kwargs): |
| 37 | + with self: |
| 38 | + return func(*args, **kwargs) |
| 39 | + |
| 40 | + return _acquire_compile_lock |
| 41 | + |
| 42 | + def _is_owned(self): |
| 43 | + # This method is borrowed from threading.Condition. |
| 44 | + # Return True if lock is owned by current_thread. |
| 45 | + # This method is called only if _lock doesn't have _is_owned(). |
| 46 | + if self._lock.acquire(0): |
| 47 | + self._lock.release() |
| 48 | + return False |
| 49 | + else: |
| 50 | + return True |
| 51 | + |
| 52 | + |
| 53 | +global_compiler_lock = _CompilerLock() |
| 54 | + |
| 55 | + |
| 56 | +def require_global_compiler_lock(): |
| 57 | + """Sentry that checks the global_compiler_lock is acquired.""" |
| 58 | + # Use assert to allow turning off this check |
| 59 | + assert global_compiler_lock.is_locked() |
0 commit comments