如果不能使用Thrust,当抛出异常时,释放cudaMalloc
的内存有标准方法吗?
你可以使用 RAII 惯用语,将你的cudaMalloc()
和cudaFree()
调用分别放在对象的构造函数和析构函数中。
一旦发生异常,你的析构函数将被调用,会释放已分配的内存。
如果你将这个对象包装到智能指针中(或使其像指针一样工作),你将得到 CUDA 智能指针。
cuda::shared_ptr
实现。如上所述,此实现将 std::shared_ptr
用作 CUDA 设备内存的包装器。
std::shared_ptr<T[]> data_host = std::shared_ptr<T[]>(new T[n]);
.
.
.
// In host code:
fun::cuda::shared_ptr<T> data_dev;
data_dev->upload(data_host.get(), n);
// In .cu file:
// data_dev.data() points to device memory which contains data_host;
cudasharedptr.h
),所以如果需要的话,对它进行操作将非常容易。
cudaFree()
调用放在清理函数中,当您捕获主机代码中的异常时,该函数将被调用。然而,您应该如何处理这些异常取决于您想要实现的目标,如果没有更多细节,我们将无法为您提供帮助。 - BenC