我目前正在尝试使用仅在设备端使用的类制作一段 CUDA 代码(即主机不需要知道它的存在)。但是我无法为班级制定正确的限定词(deviceclass
如下):
__device__ float devicefunction (float *x) {return x[0]+x[1];}
class deviceclass {
private:
float _a;
public:
deviceclass(float *x) {_a = devicefunction(x);}
float getvalue () {return _a;}
};
// Device code
__global__ void VecInit(float* A, int N)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < N) {
deviceclass *test;
test = new deviceclass(1.0, 2.0);
A[i] = test->getvalue();
}
}
// Standard CUDA guff below: Variables
float *h_A, *d_A;
// Host code
int main(int argc, char** argv)
{
printf("Vector initialization...\n");
int N = 10000;
size_t size = N * sizeof(float);
// Allocate
h_A = (float*)malloc(size);
cudaMalloc(&d_A, size);
printf("Computing...\n");
// Invoke kernel
int threadsPerBlock = 256;
int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
VecInit<<<blocksPerGrid, threadsPerBlock>>>(d_A, N);
// Copy result from device memory to host memory
cudaMemcpy(h_A, d_A, size, cudaMemcpyDeviceToHost);
//...etc
}
设置Deviceclass
为 a__device__
会引发错误,因为它是从全局函数调用的,但是将其设置为__device__ __host__
or__global__
似乎是不必要的。有人可以指出我正确的方向吗?