Skip to content

Commit

Permalink
Extend the cms::cuda::ScopedSetDevice interface
Browse files Browse the repository at this point in the history
Add a default constructor that stores the current devices, without
changing it.

Add a set() method to change the current device, without affecting the
stored value for the original device.
  • Loading branch information
fwyzard committed Aug 19, 2021
1 parent 03b30c3 commit f34db22
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions HeterogeneousCore/CUDAUtilities/interface/ScopedSetDevice.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,32 @@ namespace cms {
namespace cuda {
class ScopedSetDevice {
public:
explicit ScopedSetDevice(int newDevice) {
cudaCheck(cudaGetDevice(&prevDevice_));
cudaCheck(cudaSetDevice(newDevice));
// Store the original device, without setting a new one
ScopedSetDevice() {
cudaCheck(cudaGetDevice(&originalDevice_));
}

// Store the original device, and set a new current device
explicit ScopedSetDevice(int device) : ScopedSetDevice() {
set(device);
}

// Restore the original device
~ScopedSetDevice() {
// Intentionally don't check the return value to avoid
// exceptions to be thrown. If this call fails, the process is
// doomed anyway.
cudaSetDevice(prevDevice_);
cudaSetDevice(originalDevice_);
}

// Set a new current device, without changing the original device
// that will be restored when this object is destroyed
void set(int device) {
cudaCheck(cudaSetDevice(device));
}

private:
int prevDevice_;
int originalDevice_;
};
} // namespace cuda
} // namespace cms
Expand Down

0 comments on commit f34db22

Please sign in to comment.