【问题标题】:CUDA threads output different valueCUDA线程输出不同的值
【发布时间】:2011-07-03 08:34:33
【问题描述】:

哈,

我写了一个cuda程序,下面给出了内核函数。设备内存是
通过CUDAMalloc()分配; *md 的值为 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;
   }

}

执行了上面的代码

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

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

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

1) 我怀疑 cudaMalloc() 是否会在设备主内存中分配? 2) 为什么上面的程序总是只执行最后一个线程?

谢谢

【问题讨论】:

  • 有一堆错误。检查您的退货状态,您编写了您不知道的段错误。

标签: cuda


【解决方案1】:

您的代码中的每个线程都将不同的输出写入同一位置 (md)。因此,当程序完成执行时,md 可以有 4-5 个可能值中的任何一个。

如果你想捕捉每个线程的输出,你应该这样做

// 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

    }

执行代码为

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] = ..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    相关资源
    最近更新 更多