forked from NVIDIA-RTX/RTXNTC-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCudaDeviceGuard.cpp
More file actions
63 lines (54 loc) · 1.66 KB
/
CudaDeviceGuard.cpp
File metadata and controls
63 lines (54 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* SPDX-FileCopyrightText: Copyright (c) 2023-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: LicenseRef-NvidiaProprietary
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "CudaDeviceGuard.h"
#include "Context.h"
#include "Errors.h"
#include <cuda_runtime_api.h>
namespace ntc
{
CudaDeviceGuard::CudaDeviceGuard(Context const* context)
{
int device = context->GetCudaDevice();
if (device >= 0)
{
int originalDevice = -1;
cudaError_t err = cudaGetDevice(&originalDevice);
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaGetDevice", err);
return;
}
if (originalDevice == device)
{
// Current device is the requested one: do nothing and don't need to restore it later
m_success = true;
return;
}
// Remember the original device ID to restore in the destructor
m_originalDevice = originalDevice;
err = cudaSetDevice(device);
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaSetDevice", err);
return;
}
m_success = true;
}
}
CudaDeviceGuard::~CudaDeviceGuard()
{
if (m_originalDevice >= 0)
{
cudaSetDevice(m_originalDevice);
}
}
}