|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include <mutex> |
| 8 | +#include <unordered_map> |
| 9 | +#include <vector> |
| 10 | + |
| 11 | +#include <kvikio/shim/cuda.hpp> |
| 12 | + |
| 13 | +namespace kvikio::detail { |
| 14 | +/** |
| 15 | + * @brief Thread-safe singleton pool for reusable CUDA events |
| 16 | + * |
| 17 | + * Manages a pool of CUDA events organized by CUDA context. Events are retained and reused across |
| 18 | + * calls to minimize allocation overhead. Each context maintains its own separate pool of events |
| 19 | + * since CUDA events are context-specific resources. |
| 20 | + * |
| 21 | + * All events are created with `CU_EVENT_DISABLE_TIMING` for minimal overhead. |
| 22 | + * |
| 23 | + * Call `CudaEventPool::instance().get()` to acquire an event that is bound to the CUDA context |
| 24 | + * currently set on the calling thread. The event will be automatically returned to the pool when it |
| 25 | + * goes out of scope (RAII). |
| 26 | + * |
| 27 | + * @note The destructor intentionally does NOT call `cuEventDestroy` on cached events. |
| 28 | + * `CudaEventPool::instance()` is a function-local static destructed after `main` returns, and |
| 29 | + * making CUDA driver API calls from a static object's destructor at that point is undefined |
| 30 | + * behavior per the CUDA programming guide: |
| 31 | + * https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/intro-to-cuda-cpp.html#runtime-initialization |
| 32 | + * The OS reclaims process memory at exit regardless. |
| 33 | + */ |
| 34 | +class CudaEventPool { |
| 35 | + public: |
| 36 | + /** |
| 37 | + * @brief RAII wrapper for a pooled CUDA event |
| 38 | + * |
| 39 | + * Automatically returns the event to the pool when destroyed. Provides access to the underlying |
| 40 | + * CUevent handle and common event operations (record, synchronize). |
| 41 | + * |
| 42 | + * @note Non-copyable but movable to allow transfer of ownership while maintaining RAII |
| 43 | + */ |
| 44 | + class CudaEvent { |
| 45 | + friend class CudaEventPool; |
| 46 | + |
| 47 | + private: |
| 48 | + CudaEventPool* _pool{}; |
| 49 | + CUevent _event{}; |
| 50 | + CUcontext _cuda_context{}; |
| 51 | + |
| 52 | + /** |
| 53 | + * @brief Construct a CudaEvent wrapping a CUDA event handle |
| 54 | + * |
| 55 | + * @param pool The owning CudaEventPool to return this event to on destruction |
| 56 | + * @param event The CUDA event handle to wrap |
| 57 | + * @param context The CUDA context associated with this event |
| 58 | + */ |
| 59 | + explicit CudaEvent(CudaEventPool* pool, CUevent event, CUcontext context) noexcept; |
| 60 | + |
| 61 | + public: |
| 62 | + ~CudaEvent() noexcept; |
| 63 | + |
| 64 | + // Move-only |
| 65 | + CudaEvent(CudaEvent const&) = delete; |
| 66 | + CudaEvent& operator=(CudaEvent const&) = delete; |
| 67 | + CudaEvent(CudaEvent&& o) noexcept; |
| 68 | + CudaEvent& operator=(CudaEvent&& o) noexcept; |
| 69 | + |
| 70 | + /** |
| 71 | + * @brief Get the underlying CUDA event handle |
| 72 | + * |
| 73 | + * @return The CUevent handle wrapped by this object |
| 74 | + */ |
| 75 | + [[nodiscard]] CUevent get() const noexcept; |
| 76 | + |
| 77 | + /** |
| 78 | + * @brief Get the CUDA context associated with this event |
| 79 | + * |
| 80 | + * @return The CUcontext this event belongs to. Returns nullptr for a moved-from CudaEvent. |
| 81 | + */ |
| 82 | + [[nodiscard]] CUcontext cuda_context() const noexcept; |
| 83 | + |
| 84 | + /** |
| 85 | + * @brief Record the event on a CUDA stream |
| 86 | + * |
| 87 | + * Records the event to capture the current state of the stream. The event will be signaled when |
| 88 | + * all preceding operations on the stream have completed. |
| 89 | + * |
| 90 | + * @param stream The CUDA stream to record the event on. Must belong to the same context as this |
| 91 | + * event. Otherwise CUDA returns an error. |
| 92 | + * |
| 93 | + * @exception kvikio::CUfileException if the record operation fails |
| 94 | + */ |
| 95 | + void record(CUstream stream); |
| 96 | + |
| 97 | + /** |
| 98 | + * @brief Block the calling thread until the event has been signaled |
| 99 | + * |
| 100 | + * Waits for all work captured by a preceding record() call to complete. |
| 101 | + * |
| 102 | + * @exception kvikio::CUfileException if the synchronize operation fails |
| 103 | + */ |
| 104 | + void synchronize(); |
| 105 | + |
| 106 | + /** |
| 107 | + * @brief Non-blocking check whether all work captured by the event has completed. |
| 108 | + * |
| 109 | + * Returns true if all work captured by a preceding `record()` call has completed, false if work |
| 110 | + * is still pending. This is the non-blocking counterpart to `synchronize()`. |
| 111 | + * |
| 112 | + * @note An event that has never been recorded by `cudaAPI::instance().EventRecord()` reports |
| 113 | + * `is_done() == true`, since CUDA's `cuEventQuery` returns `CUDA_SUCCESS` when there is no |
| 114 | + * captured work. Users that rely on `is_done() == true` as a clean baseline signal should |
| 115 | + * `synchronize()` before dropping the event so that the next pool acquirer |
| 116 | + * `CudaEventPool::instance().get()` sees an idle state. |
| 117 | + * |
| 118 | + * @return true if the event has completed (or has never been recorded), false if work is still |
| 119 | + * in progress. |
| 120 | + * |
| 121 | + * @exception kvikio::CUfileException if the underlying `cuEventQuery` returns an error other |
| 122 | + * than `CUDA_SUCCESS` or `CUDA_ERROR_NOT_READY`. |
| 123 | + */ |
| 124 | + [[nodiscard]] bool is_done() const; |
| 125 | + }; |
| 126 | + |
| 127 | + private: |
| 128 | + std::mutex mutable _mutex; |
| 129 | + // Per-context pools of free events |
| 130 | + std::unordered_map<CUcontext, std::vector<CUevent>> _pools; |
| 131 | + |
| 132 | + CudaEventPool() = default; |
| 133 | + |
| 134 | + // Intentionally `noexcept = default`. See the class-level @note above: issuing CUDA driver |
| 135 | + // API calls (e.g., cuEventDestroy) from this destructor would be UB because the singleton is |
| 136 | + // destructed after main returns. The defaulted destructor runs ~_pools, which tears down the |
| 137 | + // std::vector<CUevent> entries without touching the handles. |
| 138 | + ~CudaEventPool() noexcept = default; |
| 139 | + |
| 140 | + /** |
| 141 | + * @brief Return an event to the pool for reuse |
| 142 | + * |
| 143 | + * Called by CudaEvent's destructor (and move-assignment operator) via the friend declaration. |
| 144 | + * Adds the event to the pool associated with its context for future reuse. |
| 145 | + * |
| 146 | + * @param event The CUDA event handle to return |
| 147 | + * @param context The CUDA context associated with the event |
| 148 | + * |
| 149 | + * @note noexcept: any failure inside push_back (e.g., allocator failure) is caught and logged. |
| 150 | + * The event is then destroyed instead of being cached. |
| 151 | + */ |
| 152 | + void put(CUevent event, CUcontext context) noexcept; |
| 153 | + |
| 154 | + public: |
| 155 | + // Non-copyable, non-movable singleton |
| 156 | + CudaEventPool(CudaEventPool const&) = delete; |
| 157 | + CudaEventPool& operator=(CudaEventPool const&) = delete; |
| 158 | + CudaEventPool(CudaEventPool&&) = delete; |
| 159 | + CudaEventPool& operator=(CudaEventPool&&) = delete; |
| 160 | + |
| 161 | + /** |
| 162 | + * @brief Acquire a CUDA event for the CUDA context currently set on the calling thread. |
| 163 | + * |
| 164 | + * Returns a cached event for the current CUDA context if available, otherwise creates a new one. |
| 165 | + * The returned CudaEvent object will automatically return the event to the pool when it goes out |
| 166 | + * of scope. |
| 167 | + * |
| 168 | + * @return RAII CudaEvent object wrapping the acquired CUDA event |
| 169 | + * @exception kvikio::CUfileException if no CUDA context is current or event creation fails |
| 170 | + */ |
| 171 | + [[nodiscard]] CudaEvent get(); |
| 172 | + |
| 173 | + /** |
| 174 | + * @brief Get the number of free events for a specific context |
| 175 | + * |
| 176 | + * @param context The CUDA context to query |
| 177 | + * @return The number of events available for reuse in that context's pool |
| 178 | + */ |
| 179 | + [[nodiscard]] std::size_t num_free_events(CUcontext context) const; |
| 180 | + |
| 181 | + /** |
| 182 | + * @brief Get the total number of free events across all contexts |
| 183 | + * |
| 184 | + * @return The total count of events available for reuse |
| 185 | + */ |
| 186 | + [[nodiscard]] std::size_t total_free_events() const; |
| 187 | + |
| 188 | + /** |
| 189 | + * @brief Get the singleton instance of the event pool |
| 190 | + * |
| 191 | + * @return Reference to the singleton CudaEventPool instance |
| 192 | + */ |
| 193 | + static CudaEventPool& instance(); |
| 194 | +}; |
| 195 | +} // namespace kvikio::detail |
0 commit comments