user1612986
user1612986

Reputation: 1415

C++ data structures and CUDA

i have a structure which can be

  struct type1{ double a,b,c;}

or it can be

  struct type2{ double a,b,c,d,e;}

in my host function of cuda code i have someting like

  void compute(){
      // some code
      // data on devices (up to 10) 
      type *xxx[10];   // this is where i want either type1 or type2 structures
                       // the "type" is not known at compile time but i want to 
                       // determine at runtime based on some input variable. this 
                       // part is not real code rather this is what i want to achive.

      int DevUsed;    // some code to give value to int DevUsed

      for(int idev=0;idev<DevUsed;idev++){

           // set cuda device

          if ( cudaMalloc(&xxx[iDev], sizeof(type)) != cudaSuccess )
            // print error message;
          cudaMemcpy(xxx[iDev], pIF1, sizeof(type), cudaMemcpyHostToDevice);

          function2<<<grid, block>>>(xxx[iDev]);  // where function2 is the kernel
       }
   }

My question is what is a way to select between type1 and type2 data struct with generic code like "type *xxx[10];"

Upvotes: 1

Views: 1155

Answers (1)

kangshiyin
kangshiyin

Reputation: 9781

C++ template is designed for this situation.

template <class T>
void compute(){
  // some code
  // data on devices (up to 10) 
  T xxx[10];   // this is where i want either type1 or type2 structures
                   // the "type" is not known at compile time but i want to 
                   // determine at runtime based on some input variable. this 
                   // part is not real code rather this is what i want to achive.

  int DevUsed;    // some code to give value to int DevUsed

  for(int idev=0;idev<DevUsed;idev++){

       // set cuda device

      if ( cudaMalloc(&xxx[iDev], sizeof(T)) != cudaSuccess )
        // print error message;
      cudaMemcpy(xxx[iDev], pIF1, sizeof(T), cudaMemcpyHostToDevice);

      function2<<<grid, block>>>(xxx[iDev]);  // where function2 is the kernel
   }
}

Please note that you will also need a kernel template for these two types like

template <class T>
__global__ void function2(T x)
{
    //....
}

Upvotes: 1

Related Questions