为 cuda 中的 _global_ 函数分配设备内存

Particular Allocating device memory for _global_ function in cuda

想在cuda上做这个程序。

1.in "main.cpp"

struct Center{
double * Data;
int dimension;
};
typedef struct Center Center;

//I allow a pointer on N Center elements by the CUDAMALLOC like follow

....
#include "kernel.cu"
....
center *V_dev;
int M =100, n=4; 

cudaStatus = cudaMalloc((void**)&V_dev,M*sizeof(Center));
Init<<<1,M>>>(V_dev, M, N); //I always know the dimension of N before calling

我的 "kernel.cu" 文件是这样的

#include "cuda_runtime.h"
#include"device_launch_parameters.h"
... //other include headers to allow my .cu file to know the Center type definition

__global__ void Init(Center *V, int N, int dimension){
V[threadIdx.x].dimension = dimension;
V[threadIdx.x].Data = (double*)malloc(dimension*sizeof(double));
for(int i=0; i<dimension; i++)
    V[threadIdx.x].Data[i] = 0; //For the value, it can be any kind of operation returning a float that i want to be able put here

} 

我正在使用 visual studio 2008 和 CUDA 5.0。当我构建我的项目时,我遇到了这些错误:

error: calling a _host_ function("malloc") from a _global_ function("Init") is not allowed.

我想知道如何执行此操作? (我知道 'malloc' 和其他 cpu 内存分配不允许用于设备内存。

您需要编译器参数 -arch=sm_20 和支持它的 GPU。

malloc allowed in device code 但您必须针对 cc2.0 或更高版本的目标 GPU 进行编译。

调整您的 VS 项目设置以删除任何 GPU 设备设置,例如 compute_10,sm_10 并将其替换为 compute_20,sm_20 或更高版本以匹配您的 GPU。 (而且,要 运行 该代码,您的 GPU 需要为 cc2.0 或更高版本。)