|
cuda动态共享内存与报错调试HandleError
如果你想在一个核函数中动态地申请多个数组时该怎么办呢?看附件的图片
- #include <stdio.h>
- #define N 10
- #define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))
- static void HandleError( cudaError_t err,
- const char *file,
- int line ) {
- if (err != cudaSuccess) {
- printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
- file, line );
- exit( EXIT_FAILURE );
- }
- }
- __global__ void add( int *a, int *b, int *c ) {
- int tid = threadIdx.x; // this thread handles the data at its thread id
- //使用了未指定大小的extern数组语法来声明共享内存数组
- //注意中括号与extern说明符
- //当核函数被启动时,数组大小从第三个执行配置参数被隐式地确定
- extern __shared__ int sh[]; // cuda动态共享内存的申明
- int *x = (int *)sh; //动态内存的大小在调用时候的 第三个参数上
-
- if (tid >= N)
- return;
- x[tid] = a[tid] + b[tid];
- // 这里用共享内存是多此一举 为了展示用法而已
- c[tid] = x[tid];
- }
- //cuda动态共享内存与报错调试HandleError
- //如果你想在一个核函数中动态地申请多个数组时该怎么办呢?看附件的图片
- int main( void ) {
- int a[N], b[N], c[N];
- int *dev_a, *dev_b, *dev_c;
- // allocate the memory on the GPU
- HANDLE_ERROR( cudaMalloc( (void**)&dev_a, N * sizeof(int) ) );
- HANDLE_ERROR( cudaMalloc( (void**)&dev_b, N * sizeof(int) ) );
- HANDLE_ERROR( cudaMalloc( (void**)&dev_c, N * sizeof(int) ) );
- // fill the arrays 'a' and 'b' on the CPU
- for (int i=0; i<N; i++) {
- a[i] = -i;
- b[i] = i * i;
- }
- // copy the arrays 'a' and 'b' to the GPU
- HANDLE_ERROR( cudaMemcpy( dev_a, a, N * sizeof(int),
- cudaMemcpyHostToDevice ) );
- HANDLE_ERROR( cudaMemcpy( dev_b, b, N * sizeof(int),
- cudaMemcpyHostToDevice ) );
- //cuda共享内存的动态分配 这里有三个参数:block_num,thread_num,共享内存大小
- //每个线程块中共享内存的大小必须在核函数第三个执行配置参数中指定(以字节为单位)
- add<<<1,N,N>>>( dev_a, dev_b, dev_c );
- // copy the array 'c' back from the GPU to the CPU
- HANDLE_ERROR( cudaMemcpy( c, dev_c, N * sizeof(int),
- cudaMemcpyDeviceToHost ) );
- // display the results
- for (int i=0; i<N; i++) {
- printf( "%d + %d = %d\n", a[i], b[i], c[i] );
- }
- // free the memory allocated on the GPU
- HANDLE_ERROR( cudaFree( dev_a ) );
- HANDLE_ERROR( cudaFree( dev_b ) );
- HANDLE_ERROR( cudaFree( dev_c ) );
- return 0;
- }
复制代码
|
|