【问题标题】:cudamemcpy array of pointers where each pointer points to an arraycudamemcpy 指针数组,其中每个指针指向一个数组
【发布时间】:2017-08-23 03:02:54
【问题描述】:

我正在尝试在主机上创建一个指针数组。数组中的每个指针都指向一个大小为 4 的数组。当我尝试将指针复制到设备时,复制失败并且设备无法访问指针指向的数组的内容。如何将指针数组中的指针从指向主机的数组复制到设备?

__global__ void kernel(int* D)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    while (tid < 4)
    {
        printf("Device = %d\n", D[tid]);
        tid += blockDim.x * gridDim.x;
    }
}

int main(void)
{
    cudaProfilerStart();

    int* H[2];
    int* D[2]; 
    int test1[4] = { 1, 2, 3, 4 };
    int test2[4] = { 10, 20, 30, 40 };

    H[0] = test1;
    H[1] = test2;

    HANDLE_ERROR(cudaMalloc((void**)&D[0], 4 * sizeof(int)));
    HANDLE_ERROR(cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice));
    kernel <<<1, 4 >>>(D[0]);

    cudaProfilerStop();

    return 0;
}

【问题讨论】:

  • 您发布的代码没有任何问题,它按我的预期工作。你确定你有一个功能性的 CUDA 安装吗?如果您使用它运行代码,cuda-memcheck 会报告哪些运行时错误?

标签: arrays pointers cuda


【解决方案1】:

正如 talonmies 所指出的,《守则》没有任何问题。但是,您不会在内核中看到打印,原因是内核调用是异步的,并且您的进程在内核打印可以执行之前结束。同步调用将在这里解决这个问题。但是,在实际代码中可能不需要。

#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <stdio.h>



__global__ void kernel(int* D)
{
        int tid = threadIdx.x + blockIdx.x * blockDim.x;
        while (tid < 4)
        {
                printf("Device = %d\n", D[tid]);
                tid += blockDim.x * gridDim.x;
        }
}

int main(void)
{
        // cudaProfilerStart();

        int* H[2];
        int* D[2];
        int test1[4] = { 1, 2, 3, 4 };
        int test2[4] = { 10, 20, 30, 40 };

        H[0] = test1;
        H[1] = test2;

        cudaMalloc((void**)&D[0], 4 * sizeof(int));
        cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice);
        kernel <<<1, 1 >>>(D[0]);

        cudaError_t cudaerr1 = cudaDeviceSynchronize();
        if (cudaerr1 != cudaSuccess)
                printf("kernel launch failed with error \"%s\".\n",
                        cudaGetErrorString(cudaerr1));

         //cudaProfilerStop();

        return 0;
}

【讨论】:

  • 这是否也会导致 cuda profiler 不显示时间线?
  • 是的,nvprof 分析器给了我这个错误“警告:在结果中发现 1 条无效记录。警告:如果设备内存不足或设备内核因断言而停止,则可能会发生这种情况. "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 2021-02-07
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多