【问题标题】:Cuda how do you use a pointer array with __constant__Cuda 你如何使用带有 __constant__ 的指针数组
【发布时间】:2020-05-05 21:28:24
【问题描述】:

我需要动态调整在内核实例的每个线程中查询的 int* 指针数组的大小。

我的目标是创建一个整数数组,直到运行时我才知道数组的大小(因此它不能是固定大小)。

当我这样做时:

#include "CudaTest.cuh"
#include <stdio.h>
#include <iostream>
#include <ctime>

using namespace std;

__constant__ int* deviceArray;

bool CHECK(cudaError_t type)
{
    bool flag = true;
    const cudaError_t error = type;
    if (error != cudaSuccess)
    {
        printf("\n\n Error: %s:%d, ", __FILE__, __LINE__);
        printf("\n\n code:%d, reason: %s\n", error, cudaGetErrorString(error));
        flag = false;
    }
    return flag;
}

__global__
void myKernel()
{


    //=> // constValue should be 57. But getting an Invalid memory access error here. 
    int constValue = deviceArray[7];
    printf("\n deviceArray[7]; is: %i \n", constValue);

}


int main()
{
    int* hostAry = new int[8]();

    hostAry[7] = 57;
    CHECK(cudaMemcpyToSymbol(deviceArray, hostAry, sizeof(hostAry), 0, cudaMemcpyHostToDevice));

    myKernel << < 1, 1 >> > ();
    CHECK(cudaDeviceSynchronize());
    return 0;
}

我收到此错误: 错误:

code:700,原因:遇到非法内存访问

主机阵列的内存不会被复制到 deviceArray。 我的头撞墙了,这通常意味着我根本不懂一些东西。

【问题讨论】:

  • 常量内存变量是一个指针。您没有在任何地方为 devicearray 分配任何内存。显然这是行不通的
  • 非常感谢您的回复。你能分享一个简单的例子来说明如何根据上面的例子分配这个吗?
  • __constant__ int deviceArray[8];?

标签: arrays pointers cuda int gpu


【解决方案1】:

__constant__如何使用指针数组

你没有。这是不可能的。

常量内存必须在编译时静态定义。这意味着如果您想要一个常量内存数组,则必须在编译代码时定义其大小。没有办法动态分配常量内存。

唯一现实的解决方案是将__constant__ 数组定义为最大大小,然后定义第二个__constant__ 变量,指示用于给定内核调用的数组大小。所以像:

__constant__ int devicearray[MAXSIZE];
__constant__ int devicearray_n;

在启动内核之前,将您需要的数据复制到devicearray,并将元素数量复制到devicearray_n

【讨论】:

    猜你喜欢
    • 2014-08-14
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2016-12-23
    相关资源
    最近更新 更多