Skip to content

Commit

Permalink
Apply _MembersNeededForFinalize pattern to _event.py
Browse files Browse the repository at this point in the history
  • Loading branch information
rwgk committed Nov 30, 2024
1 parent 765ff71 commit 26ddbf6
Showing 1 changed file with 19 additions and 17 deletions.
36 changes: 19 additions & 17 deletions cuda_core/cuda/core/experimental/_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,29 @@ 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()."
)

@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
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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)

0 comments on commit 26ddbf6

Please sign in to comment.