【cuda大师班】p12 主机和设备之间的数据传递

一.主机和设备之间的数据传递
1.1 基本流程框图
在这里插入图片描述
1.2 数据传递函数
在主机和设备之间必须显式的传递数据
在这里插入图片描述
1.3 代码
使用h_ 表示某个变量是主机变量
使用d_ 表示某个变量是主机变量

在这里插入图片描述

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <time.h>

__global__ void mem_trs_test(int* input)
{
    
    

	int gid = blockIdx.x * blockDim.x + threadIdx.x;
	printf(" tid : %d,gid : %d ,value: %d \n",
		threadIdx.x, gid, input[gid]);

}

int main()
{
    
    
	int size = 128;
	int byte_size = sizeof(int) * size;
	
	int* h_input;
	h_input = (int*)malloc(byte_size);

	time_t t;
	srand((unsigned)time(&t));

	for (int i = 0; i < size; i++)
	{
    
    
		h_input[i] = (int)(rand() & 0xff);
		printf("%d ", h_input[i]);
	}

	//在device中分配内存
	int* d_input;
	cudaMalloc((void**)&d_input, byte_size);
			//转化为泛型指针
	cudaMemcpy(d_input, h_input, byte_size, cudaMemcpyHostToDevice);

	dim3 block(64);
	dim3 grid(2);


	//访问全局
	mem_trs_test << <grid, block >> > (d_input);

	cudaDeviceSynchronize();
	//回收
	cudaFree(d_input);
	free(h_input);

	cudaDeviceReset();

	return 0;
}

使用指针直接指定是有弊端的。提供线程数(32的倍数)和需要的线程数(可能不是32的倍数)可能不能一一对应,余下线程应该不进行操作。

线程检查

__global__ void mem_trs_test2(int* input,int size)
{
    
    

	int gid = blockIdx.x * blockDim.x + threadIdx.x;
	//在执行前检查size
	if (gid < size)
	{
    
    
		printf(" tid : %d,gid : %d ,value: %d \n",
			threadIdx.x, gid, input[gid]);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_50862344/article/details/130448857