Cuda 你如何使用 __constant__ 的指针数组
Cuda how do you use a pointer array with __constant__
我需要动态调整在内核实例的每个线程中查询的 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;
}
我收到这个错误:
错误:
代码:700,原因:遇到非法内存访问
主机阵列的内存没有被复制到设备阵列。
我正在用头撞墙,这通常意味着我根本不了解某些东西。
How do you use a pointer array with __constant__
你不知道。不可能。
常量内存必须在编译时静态定义。这意味着如果您想要一个常量内存数组,则必须在编译代码时定义大小。没有办法动态分配常量内存。
唯一现实的解决方案是定义一个 __constant__
数组的最大大小,然后是第二个 __constant__
变量,指示用于给定内核调用的数组大小。所以像:
__constant__ int devicearray[MAXSIZE];
__constant__ int devicearray_n;
在启动内核之前,将您需要的数据复制到 devicearray
并将元素数量复制到 devicearray_n
。
我需要动态调整在内核实例的每个线程中查询的 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;
}
我收到这个错误: 错误:
代码:700,原因:遇到非法内存访问
主机阵列的内存没有被复制到设备阵列。 我正在用头撞墙,这通常意味着我根本不了解某些东西。
How do you use a pointer array with
__constant__
你不知道。不可能。
常量内存必须在编译时静态定义。这意味着如果您想要一个常量内存数组,则必须在编译代码时定义大小。没有办法动态分配常量内存。
唯一现实的解决方案是定义一个 __constant__
数组的最大大小,然后是第二个 __constant__
变量,指示用于给定内核调用的数组大小。所以像:
__constant__ int devicearray[MAXSIZE];
__constant__ int devicearray_n;
在启动内核之前,将您需要的数据复制到 devicearray
并将元素数量复制到 devicearray_n
。