title: CUDA porting of a struct with internal random function
body: <p>I have to port on a GPU a structure that use extensively the random numbers.   Everything could be ported without a lot of problems but the random generator function is the only thing that it's called extensively in all the function of this class.
  I though I could simply reimplement it as a internal device function of the class itself.
  Below I put a toy model of what I need (take in consideration that the class with which I am working is more complicated).
  I need also that each call of the function "rand" give a different random number (even in the same object).
  Here the toy model, however it produce wrong results.  Could anyone help me to correct it please?</p>
  
  <pre><code>#include &lt;cuda.h&gt;
  #include &lt;iostream&gt;
  #include &lt;curand_kernel.h&gt;
  using namespace std;
  
  struct test{
  
  float value;
  
  curandState B;
  
  void __device__ rand(){value=curand_uniform(&amp;B);}
  void __device__ foo(){rand();}
  };
  
  __global__ void setup_kernel(curandState *state)
  {
  const int id=blockIdx.x;
  curand_init(id, id, 0, &amp;state[id]);
  }
  
  __global__ void fill_mat(struct test *anobj, curandState *state)
  {
   const int Idx=blockIdx.x;
   curandState localState = state[Idx];
   anobj[Idx].B=localState;
   anobj[Idx].foo();
  }
  
  int main()
  {
  int num=10;
  curandState *devStates;
  cudaMalloc(  (void **)&amp;devStates, num*sizeof(curandState) );
  
  struct test *results = (struct test*)malloc(num*sizeof(struct test));
  struct test *to_device;
  cudaMalloc ( (void **)&amp;to_device, num*sizeof(to_device));
  
  setup_kernel&lt;&lt;&lt;num, 1&gt;&gt;&gt;(devStates);
  
  fill_mat&lt;&lt;&lt;num,1&gt;&gt;&gt;(to_device, devStates);
  
  cudaMemcpy(results,to_device,num*sizeof(struct test),cudaMemcpyDeviceToHost);
  
  for(int i=0;i&lt;num;i++)
   cout&lt;&lt;results[i].value&lt;&lt;endl; 
  return 0;
  }
  </code></pre>