使用vector <complex <long double =“”>> C ++进行cudaMalloc管理-NVIDIA CUDA

时间:2018-06-27 17:32:19

标签: c++ vector cuda

我正在通过NVIDIA GeForce GT 650M GPU实施多线程,以进行我创建的仿真。为了确保一切正常,我创建了一些辅助代码来测试一切正常。一方面,我需要更新变量向量(它们都可以单独更新)。

这是要点:

`\__device__
int doComplexMath(float x, float y)
{
    return x+y;
}`

`// Kernel function to add the elements of two arrays
__global__
void add(int n, float *x, float *y, vector<complex<long double> > *z)
{
    int index = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;
    for (int i = index; i < n; i += stride)
        z[i] = doComplexMath(*x, *y);
}`

`int main(void)
{
    int iGAMAf = 1<<10;
    float *x, *y;
    vector<complex<long double> > VEL(iGAMAf,zero);
    // Allocate Unified Memory – accessible from CPU or GPU
    cudaMallocManaged(&x, sizeof(float));
    cudaMallocManaged(&y, sizeof(float));
    cudaMallocManaged(&VEL, iGAMAf*sizeof(vector<complex<long double> >));
    // initialize x and y on the host
    *x = 1.0f;
    *y = 2.0f;
    // Run kernel on 1M elements on the GPU
    int blockSize = 256;
    int numBlocks = (iGAMAf + blockSize - 1) / blockSize;
    add<<<numBlocks, blockSize>>>(iGAMAf, x, y, *VEL);
    // Wait for GPU to finish before accessing on host
    cudaDeviceSynchronize();
    return 0;
}`

我正在尝试分配统一内存(可从GPU和CPU访问的内存)。使用nvcc进行编译时,出现以下错误:

错误:没有任何重载函数“ cudaMallocManaged”的实例与参数列表匹配             参数类型为:(std :: __ 1 :: vector,std :: __ 1 :: allocator >> *,无符号长)

如何在CUDA中正确重载该函数以在多线程中使用此类型?

1 个答案:

答案 0 :(得分:2)

无法做您想做的事情。

要使用托管内存分配向量,您将必须编写自己的分配器实现,该实现从std::allocator_traits继承并在后台调用cudaMallocManaged。然后,您可以使用分配器类实例化std::vector

还要注意,您的CUDA内核代码已损坏,因为您无法在设备代码中使用std::vector

请注意,尽管该问题已考虑了托管内存,但这适用于其他类型的CUDA分配,例如固定分配。

作为另一种建议here,您可以考虑使用推力宿主向量代替std::vector,并使用自定义分配器。在固定分配器(cudaMallocHost / cudaHostAlloc的情况下,有效的示例是here