I need a device version of the following
host code:
double (**func)(double x);
double func1(double x)
{
return x+1.;
}
double func2(double x)
{
return x+2.;
}
double func3(double x)
{
return x+3.;
}
void test(void)
{
double x;
for(int i=0;i<3;++i){
x=func[i](2.0);
printf("%g
",x);
}
}
int main(void)
{
func=(double (**)(double))malloc(10*sizeof(double (*)(double)));
test();
return 0;
}
where func1, func2, func3
have to be __device__ functions
and "test"
has to be a (suitably modified) __global__ kernel.
I have a NVIDIA GeForce GTS 450 (compute capability 2.1)
Thank you in advance
Michele
========================================================
A working solution
#define REAL double
typedef REAL (*func)(REAL x);
__host__ __device__ REAL func1(REAL x)
{
return x+1.0f;
}
__host__ __device__ REAL func2(REAL x)
{
return x+2.0f;
}
__host__ __device__ REAL func3(REAL x)
{
return x+3.0f;
}
__device__ func func_list_d[3];
func func_list_h[3];
__global__ void assign_kernel(void)
{
func_list_d[0]=func1;
func_list_d[1]=func2;
func_list_d[2]=func3;
}
void assign(void)
{
func_list_h[0]=func1;
func_list_h[1]=func2;
func_list_h[2]=func3;
}
__global__ void test_kernel(void)
{
REAL x;
for(int i=0;i<3;++i){
x=func_list_d[i](2.0);
printf("%g
",x);
}
}
void test(void)
{
REAL x;
printf("=============
");
for(int i=0;i<3;++i){
x=func_list_h[i](2.0);
printf("%g
",x);
}
}
int main(void)
{
assign_kernel<<<1,1>>>();
test_kernel<<<1,1>>>();
cudaThreadSynchronize();
assign();
test();
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…