代码之家  ›  专栏  ›  技术社区  ›  Rahn

将GPU内存分配给类的成员变量的正确方法是什么?

  •  0
  • Rahn  · 技术社区  · 1 年前

    基本上我希望为类分配GPU内存 Image 的成员变量 frame 具有 cudaMallocManaged :

    class Image {
    public:
        Color* frame;
    };
    

    但通过以下代码,我得到了 CUDA error = 1 为指针分配时 框架 :

    #include <iostream>
    
    // limited version of checkCudaErrors from helper_cuda.h in CUDA examples
    #define checkCudaErrors(val) check_cuda((val), #val, __FILE__, __LINE__)
    
    void check_cuda(cudaError_t result, char const* const func, const char* const file,
                    int const line) {
        if (result) {
            std::cerr << "CUDA error = " << static_cast<unsigned int>(result) << " at " << file << ":"
                    << line << " '" << func << "' \n";
            // Make sure we call CUDA Device Reset before exiting
            cudaDeviceReset();
            exit(-1);
        }
    }
    
    class Color {
    public:
        double r, g, b;
    
        __host__ __device__ Color() : r(0.0), g(0.0), b(0.0) {
        }
    };
    
    
    class Image {
    public:
        Color* frame;
    };
    
    int main() {
        int width = 1960;
        int height = 1080;
    
        Image *image;
        checkCudaErrors(cudaMallocManaged((void **)&image, sizeof(Image)));
        checkCudaErrors(cudaMallocManaged((void **)&(image->frame), sizeof(Color) * width, height));
    
        return 0;
    }
    

    将GPU内存分配给该成员变量的正确方法是什么?

    1 回复  |  直到 1 年前
        1
  •  1
  •   463035818_is_not_an_ai    1 年前

    cudaMallocManaged 声明如下:

    __host__ ​cudaError_t cudaMallocManaged(void** devPtr, size_t size,
                                           unsigned int flags = cudaMemAttachGlobal)
    

    所以你可以使用这个:

    checkCudaErrors(cudaMallocManaged((void **)&(image->frame),
                                      sizeof(Color) * width * height));
    

    注:第三个论点, flags ,在此处左侧使用默认值 cudaMemAttachGlobal 大小是通过乘以 sizeof(Color) , width height .