【发布时间】:2017-12-08 00:54:28
【问题描述】:
我想编写一个 c++ CUDA 程序,将一个类传递给内核。该类只是通过调用 operator() 评估内核上的一个函数。如果我在课堂上硬连线函数,一切都会按我的意愿工作。但是,我希望该类具有一定的灵活性,因此我希望该类能够使用不同的功能进行实例化。通过传入一个指针函数来说。我无法让指针函数实现工作。下面我定义了两个类,一个定义了函数(fixedFunction),另一个接受了指向函数的指针(genericFunction)
//Functions.hh
#include <iostream>
#include <stdio.h>
class fixedFunction{
public:
__host__ fixedFunction() {}
__host__ __device__ double operator()(double x) {
return x*x;
}
};
double f1(double x){
return x*x;
}
typedef double (*pf) (double var);
class genericFunction{
public:
__host__ genericFunction(double (*infunc)(double)) : func(infunc){}
__host__ __device__ double operator()(double x) {
return func(x);
}
private:
pf func;
};
__global__ void kernel1(fixedFunction* g1){
unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
printf("Func val is: %f\n", (*g1)(tid));
}
__global__ void kernel2(genericFunction* g1){
unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
printf("Func val is: %f\n", (*g1)(tid));
}
实例化这两个类并在主机上运行它们是可行的。传递给相关内核,我看到该类调用指针函数的 kernel2 失败
#include "Functions.hh"
int main(){
fixedFunction h_g1;
fixedFunction* d_g1;
cudaMallocManaged(&d_g1, sizeof(h_g1));
//Host call
std::cout << h_g1(2.0) << "\n";
//device call
kernel1<<<1,32>>>(d_g1);
cudaDeviceSynchronize();
genericFunction h_g2(f1);
genericFunction* d_g2;
cudaMallocManaged(&d_g2, sizeof(h_g2));
//Host call
std::cout << h_g2(3.0) << "\n";
//device call
kernel2<<<1,32>>>(d_g2);
cudaDeviceSynchronize();
我可以看到指针函数中的问题可以是任何大小,并且在设备上没有考虑到。那么有没有办法将指针函数传递给类并在设备上运行呢?
谢谢
【问题讨论】:
-
f1 不是设备功能。无论函数指针设置是否正确,您都无法使用 from s 内核