From 26ddbf6d9685c06a1c27bf0187e45a33c18e8ef3 Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Sat, 30 Nov 2024 11:28:33 -0800 Subject: [PATCH] Apply _MembersNeededForFinalize pattern to _event.py --- cuda_core/cuda/core/experimental/_event.py | 36 ++++++++++++---------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/cuda_core/cuda/core/experimental/_event.py b/cuda_core/cuda/core/experimental/_event.py index 7b002111..f2dbf74a 100644 --- a/cuda_core/cuda/core/experimental/_event.py +++ b/cuda_core/cuda/core/experimental/_event.py @@ -51,10 +51,21 @@ class Event: """ - __slots__ = ("__weakref__", "_finalizer", "_handle", "_timing_disabled", "_busy_waited") + class _MembersNeededForFinalize: + __slots__ = ("handle",) + + def __init__(self, event_obj, handle): + self.handle = handle + weakref.finalize(event_obj, self.close) + + def close(self): + if self.handle is not None: + handle_return(cuda.cuEventDestroy(self.handle)) + self.handle = None + + __slots__ = ("__weakref__", "_mnff", "_timing_disabled", "_busy_waited") def __init__(self): - self._handle = None raise NotImplementedError( "directly creating an Event object can be ambiguous. Please call call Stream.record()." ) @@ -62,8 +73,7 @@ def __init__(self): @staticmethod def _init(options: Optional[EventOptions] = None): self = Event.__new__(Event) - # minimal requirements for the destructor - self._handle = None + self._mnff = Event._MembersNeededForFinalize(self, None) options = check_or_create_options(EventOptions, options, "Event options") flags = 0x0 @@ -77,20 +87,12 @@ def _init(options: Optional[EventOptions] = None): self._busy_waited = True if options.support_ipc: raise NotImplementedError("TODO") - self._handle = handle_return(cuda.cuEventCreate(flags)) - self._finalizer = weakref.finalize(self, Event._finalize, self._handle) + self._mnff.handle = handle_return(cuda.cuEventCreate(flags)) return self - @staticmethod - def _finalize(self_handle): - handle_return(cuda.cuEventDestroy(self_handle)) - def close(self): """Destroy the event.""" - if self._handle: - self._finalizer.Detach() - Event._finalize(self._handle) - self._handle = None + self._mnff.close() @property def is_timing_disabled(self) -> bool: @@ -117,12 +119,12 @@ def sync(self): has been completed. """ - handle_return(cuda.cuEventSynchronize(self._handle)) + handle_return(cuda.cuEventSynchronize(self._mnff.handle)) @property def is_done(self) -> bool: """Return True if all captured works have been completed, otherwise False.""" - (result,) = cuda.cuEventQuery(self._handle) + (result,) = cuda.cuEventQuery(self._mnff.handle) if result == cuda.CUresult.CUDA_SUCCESS: return True elif result == cuda.CUresult.CUDA_ERROR_NOT_READY: @@ -133,4 +135,4 @@ def is_done(self) -> bool: @property def handle(self) -> int: """Return the underlying cudaEvent_t pointer address as Python int.""" - return int(self._handle) + return int(self._mnff.handle)