kar
kar

Reputation: 2795

CUDA threads output different value

HAi,

I wrote a cuda program , i have given the kernel function below. The device memory is
allocated through CUDAMalloc(); the value of *md is 10;

__global__ void add(int *md)

{

    int x,oper=2;
    x=threadIdx.x;

   * md = *md*oper;

if(x==1)
   {
       *md = *md*0;
   }

   if(x==2)
   {
      *md = *md*10;
   }

   if(x==3)
   {
       *md = *md+1;
   }

   if(x==4)
   {
       *md = *md-1;
   }

}

executed the above code

 add<<<1,5>>(*md) , add<<<1,4>>>(*md)

for <<<1,5>>> the output is 19

for <<<1,4>>> the output is 21

1) I have doubt that cudaMalloc() will allocate in device main memory? 2) Why the last thread alone is executed always in the above program?

Thank you

Upvotes: 0

Views: 418

Answers (1)

jwdmsd
jwdmsd

Reputation: 2127

Every thread, in your code, writes a different output into same location (md). As a result when the program finishes execution md can have any one of the 4-5 possible values.

If you want to catch the output of every thread, here's what you should do

// The size of output is should be equal to the number of threads in your block
  __global__ void add (int input, int * output){  

     int x = threadIdx.x;
     int oper = 2;
      md = md*oper;


    //thread Index starts from 0 in CUDA

           if(x==0)
            output[0]= md*0;  // output is 0


          if(x==1)
            output[1] = md*10;  // output is 200


          if(x==2)
            output[2] = md+1;  // output is 21


          if(x==3)
            output[3] = md-1; // output is 19


       ..... and so on

    }

Execute the code as

int value = 10;
int * out;
int size = 5*sizeof(int);
cudaMalloc((void**)&out,size );

add<<<1,5>>(value,out)

int * host_out = (int*)malloc(size);
cudaMemcpy(host_out,out,size,cudaMemcpyDeviceToHost);

//Now the host_out should have the following values:
//host_out[0] = 0
//host_out[1] = 200
//host_out[2] = 21
//host_out[3] = 19
//host_out[4] = ..

Upvotes: 1

Related Questions