2011-11-03 81 views
8

對於在CUDA中使用原子操作,是否需要包含一些CUDA頭文件? CUDA編程指南似乎對此非常敏感。CUDA中的原子操作?包含哪個頭文件?

下面給出的代碼glmax.cu給我下面的編譯錯誤。

gaurish108 MyPractice: nvcc glmax.cu -o glmax 
glmax.cu(11): error: identifier "atomicMax" is undefined 

1 error detected in the compilation of "/tmp/tmpxft_000010fa_00000000-4_glmax.cpp1.ii". 

這是代碼。它基本上是使用原子操作​​3210來計算GPU上陣列的最大值。由於我是CUDA的新手,所以我確信這是一個非常幼稚的代碼,但是我寫這個是爲了幫助我自己理解原子操作。

#include<stdio.h> 
#include<stdlib.h> 
#include<math.h> 

__global__ void global_max(int* values, int* gl_max) 
{ 

    int i=threadIdx.x + blockDim.x * blockIdx.x; 
    int val=values[i]; 

    atomicMax(gl_max,val); 

} 


int main(void) 
{ 
    int array_size=5; 
    int num_bytes=array_size*sizeof(int); 
    int *device_array=0; 
    int *host_array=0; 

    int *device_max=0; 
    int *host_max=0; 

    //Allocate memory on the host 
    host_array=(int*)malloc(num_bytes); 

    //Allocate memory on the device 
    cudaMalloc((void**)&device_array,num_bytes); 
    cudaMalloc((void**)&device_max,sizeof(int)); 


    //If either memory allocation failed, report an error message 
    if(host_array == 0 || device_array == 0) 
    { 
    printf("couldn't allocate memory\n"); 
    return 1; 
    } 

    //Assign a random integer in the interval [0,25] to host_array members 
    for(int i=0;i<array_size;++i) 
    { 
     *(host_array+i)=rand()%26; 
    } 

    //Print the host array members 
    printf("Host Array\n"); 
    for(int i=0;i<array_size;++i) 
    { 
     printf("%d ",*(host_array+i)); 
    } 
    printf("\n"); 

    //Copy array from host to device. 
    cudaMemcpy(device_array,host_array,num_bytes,cudaMemcpyHostToDevice); 

    //Configure and launch the kernel which calculates the maximum element in the device array. 
    int grid_size=1;//Only 1 block of threads is used 
    int block_size=5;//One block contains only 5 threads 

    //Device array passed to the kernel as data. 
    global_max<<<grid_size,block_size>>>(device_array,device_max); 

    //Transfer the maximum value so calculated into the CPU and print it 
    cudaMemcpy(host_max,device_max,sizeof(int),cudaMemcpyDeviceToHost); 
    printf("\nMaximum value is %d\n",*host_max); 


    // deallocate memory 
    free(host_array); 
    cudaFree(device_array); 
    cudaFree(device_max); 
    return 0; 
} 

回答

13

我不認爲#include是必要的。 「計算能力」1.0(sm_10)設備上不提供原子操作,這是您要求nvcc進行編譯的默認設置。

要在代碼中使用​​3210,請在命令行上至少-arch=sm_11

$nvcc -arch=sm_11 glmax.cu -o glmax 

對於未來的參考,你可以什麼原子操作可諮詢CUDA C編程指南的附錄F信息在特定計算能力的平臺上。

當然,您需要一個sm_11兼容的GPU才能執行代碼。我的印象是,這些現在很普遍。

+0

謝謝。代碼編譯時沒有任何錯誤。但我在'printf(「\ n最大值是%d \ n」,* host_max)行得到分段錯誤;'但是這是另一個線程的主題,我猜:D – smilingbuddha