标签:
这个程序是把两个向量相加
add<<<N,1>>>(dev_a,dev_b,dev_c);//<N,1>,第一个参数N代表block的数量,第二个参数1代表每个block中thread的数量
tid=blockIdx.x;//blockIdx是一个内置变量,blockIdx.x代表这是一个2维索引
代码:
/*
============================================================================
Name : VectorSum-CUDA.cu
Author : can
Version :
Copyright : Your copyright notice
Description : CUDA compute reciprocals
============================================================================
*/
#include<iostream>
using namespace std;
#define N 10
__global__ void add(int *a,int *b,int *c);
static void checkCudaErrorAux(const char *,unsigned, const char *,cudaError_t);
#define CUDA_CHECK_RETURN(value) checkCudaErrorAux(__FILE__,__LINE__,#value,value)
int main()
{
int a[N],b[N],c[N];
int *dev_a,*dev_b,*dev_c;
for(int i=0;i<N;i++)
{
a[i]=i;
b[i]=i*i;
}
CUDA_CHECK_RETURN(cudaMalloc((void **)&dev_a,N*sizeof(int)));
CUDA_CHECK_RETURN(cudaMalloc((void **)&dev_b,N*sizeof(int)));
CUDA_CHECK_RETURN(cudaMalloc((void **)&dev_c,N*sizeof(int)));
CUDA_CHECK_RETURN(cudaMemcpy(dev_a,a,N*sizeof(int),cudaMemcpyHostToDevice));
CUDA_CHECK_RETURN(cudaMemcpy(dev_b,b,N*sizeof(int),cudaMemcpyHostToDevice));
add<<<N,1>>>(dev_a,dev_b,dev_c);//<N,1>,第一个参数N代表block的数量,第二个参数1代表每个block中thread的数量
CUDA_CHECK_RETURN(cudaMemcpy(c,dev_c,N*sizeof(int),cudaMemcpyDeviceToHost));
for(int j=0;j<N;j++)
{
cout<<a[j]<<" + "<<b[j]<<" = "<<c[j]<<endl;
}
return 0;
}
__global__ void add(int* a,int* b,int* c)
{
int tid=blockIdx.x;//blockIdx是一个内置变量,blockIdx.x代表这是一个2维索引
if(tid<N)//避免出错造成非法内存访问
{
c[tid]=a[tid]+b[tid];
}
}
static void checkCudaErrorAux(const char *file,unsigned line, const char *statement,cudaError_t error)
{
if(error==cudaSuccess)
{
return;
}
cout<<statement<<"returned:"<<cudaGetErrorString(error)<<" at file:"<<file<<" line:"<<line<<endl;
exit(1);
}
标签:
原文地址:http://www.cnblogs.com/shrimp-can/p/5034284.html