CUDA推力:检查NULL指针

Luc*_*uca 2 c++ cuda thrust

我试图在CUDA中使用推力,并具有以下内容:

data = thrust::device_malloc<float>(N);
Run Code Online (Sandbox Code Playgroud)

现在,我有另一个方法要检查数据指针是否正确初始化。这是正确的用法还是有更优选的方法?

if (data->get() == NULL) // throw some exception.
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,我无法直接在device_ptr对象上使用bool比较器:

if (!data) // compilation error.
Run Code Online (Sandbox Code Playgroud)

另外,如果我想使用推力:: device_free,是否需要再次检查NULL(如C风格免费),还是将推力:: device_free用于NULL输入指针是否安全?

tal*_*ies 5

thrust::device_malloc如果分配失败,则会引发异常,因此,我真的没有想到可以检查a值的device_ptr有效性或在用户代码中引发异常的情况。在每种情况下,代码都应因未捕获的异常而中止,或者您的主机捕获由推力引发的异常并做出相应的反应。

也就是说,来源thrust::device_malloc表明在内存分配失败的情况下,返回device_ptr的原始指针值将为0。您应该能够使用以下命令进行确认:

#include <thrust/device_malloc.h>
#include <thrust/device_ptr.h>
#include <iostream>
#include <new>

void try_alloc(unsigned int N)
{
    thrust::device_ptr<float> data;

    std::cout << "trying N=" << N;

    try
    {
        data = thrust::device_malloc<float>(N);
    }
    catch (std::bad_alloc& e)
    {
        std::cerr << " bad_alloc caught: " << e.what() << std::endl;
    }
    std::cout << " data.get() returns: " << std::hex << data.get() << std::endl;

}

int main()
{

    try_alloc(2<<4);
    try_alloc(2<<9);
    try_alloc(2<<14);
    try_alloc(2<<19);
    try_alloc(2<<24);
    try_alloc(2<<29);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,为了回答您的问题,

data = thrust::device_malloc<float>(N); 
Run Code Online (Sandbox Code Playgroud)

一个“正确”的测试将是

if (!data.get()) { .. } // Pointer is invalid 
Run Code Online (Sandbox Code Playgroud)

注意到a std::bad_alloc应该已经被先验地提出