这里先说明下一些基本概念:
释放GPU中的内存cudaFree()
CUDA函数的定义:
__global__:定义在GPU上,可以在CPU上调用的函数;
__device__:定义在GPU上,由GPU调用函数;
__host__:在CPU上定义的函数,一般与__device__一起用
在GPU上开辟空间:cudaMalloc(**devPtr, byte_size)
如:
int *gpu_int;
cudaMalloc((void**)&gpu_int, sizeof(int))
GPU上数组的初始化cudaMemset(*devptr, value, byte_size)
GPU、CPU参数传递cudaMemcpy(*dst, *src, byte_size, 类型)
其中这个类型包括:
CPU2CPU:cudaMemcpyHostToHost
CPU2GPU:cudaMemcpyHostToDevice
GPU2CPU:cudaMemcpyDeviceToHost
GPU2GPU:cudaMemcpyDeviceToDevice
源码如下:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
using namespace std;
__device__ int add_one(int a) {
return a + 1;
}
__global__ void show(int *a) {
for (int i = 0; i < 10; i++) {
//a[i] = add_one(a[i]);
printf(" %d", a[i]);
}
printf("\n");
}
__global__ void changeValue(int *a) {
for (int i = 0; i < 10; i++) {
a[i] = 100;
}
}
int main() {
int cpu_int[10] = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10};
int *gpu_int;
//在GPU上分配空间
cudaMalloc((void**)&gpu_int, 10 * sizeof(int));
show << <1, 1 >> > (gpu_int);
//初始化其值
cudaMemset(gpu_int, 0, 10 * sizeof(int));
show<< <1, 1 >> > (gpu_int);
//将cpu_int赋值给gpu_int
cudaMemcpy(gpu_int, cpu_int, 10 * sizeof(int), cudaMemcpyHostToDevice);
show << <1, 1 >> > (gpu_int);
//改变gpu_int的值
changeValue << <1, 1 >> >(gpu_int);
show << <1, 1 >> > (gpu_int);
//将gpu_int的值赋值到cpu_int
cudaMemcpy(cpu_int, gpu_int, 10 * sizeof(int), cudaMemcpyDeviceToHost);
printf("----------华丽的分割线----------\n");
for (int i = 0; i < 10; i++) {
printf(" %d", cpu_int[i]);
}
//释放gpu_int的空间
cudaFree(gpu_int);
getchar();
return 0;
}
程序运行截图如下:
源码打包地址如下:
https://github.com/fengfanchen/CAndCPP/tree/master/HelloCuda