|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +#include <cuvs/core/c_api.h> |
| 7 | + |
| 8 | +#include <gtest/gtest.h> |
| 9 | + |
| 10 | +#include <atomic> |
| 11 | +#include <cstddef> |
| 12 | +#include <thread> |
| 13 | +#include <vector> |
| 14 | + |
| 15 | +// Pinned host buffers may be freed on a different thread than the one that allocated them, e.g. |
| 16 | +// when a binding moves the owning object across threads. |
| 17 | +TEST(RMMHostAlloc, FreeOnAnotherThread) |
| 18 | +{ |
| 19 | + constexpr std::size_t kBytes = 1024; |
| 20 | + void* ptr = nullptr; |
| 21 | + cuvsError_t alloc_status = CUVS_ERROR; |
| 22 | + std::thread([&] { alloc_status = cuvsRMMHostAlloc(&ptr, kBytes); }).join(); |
| 23 | + ASSERT_EQ(alloc_status, CUVS_SUCCESS); |
| 24 | + ASSERT_NE(ptr, nullptr); |
| 25 | + |
| 26 | + cuvsError_t free_status = CUVS_ERROR; |
| 27 | + std::thread([&] { free_status = cuvsRMMHostFree(ptr, kBytes); }).join(); |
| 28 | + EXPECT_EQ(free_status, CUVS_SUCCESS); |
| 29 | +} |
| 30 | + |
| 31 | +TEST(RMMHostAlloc, ConcurrentAllocAndFree) |
| 32 | +{ |
| 33 | + constexpr int kThreads = 8; |
| 34 | + constexpr int kIters = 50; |
| 35 | + constexpr std::size_t kBytes = 4096; |
| 36 | + std::vector<void*> ptrs(kThreads * kIters, nullptr); |
| 37 | + std::atomic<int> failures{0}; |
| 38 | + |
| 39 | + std::vector<std::thread> threads; |
| 40 | + for (int t = 0; t < kThreads; ++t) { |
| 41 | + threads.emplace_back([&, t] { |
| 42 | + for (int i = 0; i < kIters; ++i) { |
| 43 | + if (cuvsRMMHostAlloc(&ptrs[t * kIters + i], kBytes) != CUVS_SUCCESS) { failures++; } |
| 44 | + } |
| 45 | + }); |
| 46 | + } |
| 47 | + for (auto& th : threads) { |
| 48 | + th.join(); |
| 49 | + } |
| 50 | + threads.clear(); |
| 51 | + ASSERT_EQ(failures.load(), 0); |
| 52 | + |
| 53 | + // Free every buffer from a different thread than the one that allocated it. |
| 54 | + for (int t = 0; t < kThreads; ++t) { |
| 55 | + threads.emplace_back([&, t] { |
| 56 | + int const owner = (t + 1) % kThreads; |
| 57 | + for (int i = 0; i < kIters; ++i) { |
| 58 | + if (cuvsRMMHostFree(ptrs[owner * kIters + i], kBytes) != CUVS_SUCCESS) { failures++; } |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
| 62 | + for (auto& th : threads) { |
| 63 | + th.join(); |
| 64 | + } |
| 65 | + EXPECT_EQ(failures.load(), 0); |
| 66 | +} |
0 commit comments