2011-02-24 64 views
0

HAi,CUDA线程输出不同的值

我写了一个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)I有疑问,cudaMalloc()将在设备主存储器分配? 2)为什么最后一个线程总是在上面的程序中执行?

谢谢

+0

有失误的一堆东西。检查你的返回状态,你编程段未知的段错误。 – Anycorn 2011-02-24 07:26:15

回答

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

谢谢你,我明白了 – kar 2011-02-25 04:31:03