본문 바로가기
프로그래밍 언어/C, C++ 다양한 예시들

[CUDA] 데이터 복사 예제

by Physics 2021. 8. 20.
728x90

문제 

해당 문제에선, CUDA에서 데이터를 전송하는 것을 연습한다. 이때, 
  1) 호스트 → 디바이스 
  2) 디바이스 → 디바이스 
  3) 디바이스 → 호스트
로 각각 데이터들을 전송하는 방법을 확인한다. 


1. 크기가 5인 배열을 각각 호스트에서 2개, 디바이스용 2개를 만들아라. 
    - host에서의 배열: host_A, host_B
    - device에서의 배열: device1_A, device2_A 
2. host_A의 배열에 값을 할당하라. 
3. 할당된 host_A의 값을 device1_A로 복사하라. 
    - 이때, device1_A에 할당된 값을 출력한다. 
    - 출력 후, 각각의 배열의 원소에 1을 더한다. 
4. device1_A의 값들을 device2_A로 복사하라. 
    - 3.에서와 마찬가지로 device2_A에도 동일하게 적용하라. 
5. device2_A 값을 host_B에 복사하라. 
    - host_B에 복사된 값을 출력하라. 
6. device에 할당된 메모리를 해제하라. 


코드의 예시)

#include <stdio.h>
__device__ void print_Array(int tid, int *A){

	printf("A[%d] = %d\n", tid, A[tid]);
	A[tid] = A[tid] + 1;
	if (tid == 0) printf("======================\n");
};
__global__ void Print(int *A){
	int tid = threadIdx.x;
	print_Array(tid, A);
};

int main(void){
	int *device1_A, *device2_A, *host_A, *host_B;
	int size = 5; 

	host_A = (int *)malloc(size * sizeof(int));
	host_B = (int *)malloc(size * sizeof(int));

	// Making array on host_A
	for (int i = 0; i < size; i++) host_A[i] = i;
	
	// Allocation memory of devices 
	cudaSetDevice(0);
	cudaMalloc((int**)&device1_A, size * sizeof(int));
	
	cudaSetDevice(1);
	cudaMalloc((int**)&device2_A, size * sizeof(int));

	// Data transfer : Host to Deivce 0
	cudaSetDevice(0); 
	cudaMemcpy( device1_A, host_A, size * sizeof(int), cudaMemcpyHostToDevice);
	Print<<<1,5>>>(device1_A);
	cudaDeviceSynchronize();

	// Data transfer :  Device 0 to Device 1
	cudaMemcpy(device2_A, device1_A, size * sizeof(int), cudaMemcpyDeviceToDevice);
	cudaSetDevice(1);
	Print<<<1,5>>>(device2_A);
	cudaDeviceSynchronize();

	// Data transfer : Device 1 to Host 
	cudaMemcpy(host_B, device2_A, size * sizeof(int), cudaMemcpyDeviceToHost);
	for (int i = 0; i < size; i++) printf("Host_B[%d] = %d\n", i, host_B[i]);

	cudaFree(device1_A);
	cudaFree(device2_A);

	cudaDeviceReset();

	return 0;

	cudaFree(device1_A);

}
728x90

댓글