10 static __global__ void add(float* ptrDevV1, float* ptrDevV2, int n, float* ptrDevResult);
11 static __device__ float work(float v1, float v2);
13 __global__ void add(float* ptrDevV1, float* ptrDevV2, int n, float* ptrDevResult)
15 const int NB_THREAD = Indice2D::nbThread();
16 const int TID = Indice2D::tid();
22 ptrDevResult[s] = work(ptrDevV1[s], ptrDevV2[s]);
27 __device__ float work(float v1, float v2)
34 // Inputs (passé en paramètre de la fonction dans un cas général).
35 float v1[] = { 1, 2, 3 };
36 float v2[] = { 10, 20, 30 };
38 // Outputs (renvoyer de la fonction dans un cas général).
41 // Allocation coté GPU.
42 float* ptrDevV1, *ptrDevV2, *ptrDevVResult = 0;
43 const size_t vecSize = 3 * sizeof(float);
44 HANDLE_ERROR(cudaMalloc(&ptrDevV1, vecSize));
45 HANDLE_ERROR(cudaMalloc(&ptrDevV2, vecSize));
46 HANDLE_ERROR(cudaMalloc(&ptrDevVResult, vecSize));
48 HANDLE_ERROR(cudaMemset(ptrDevV1, 0, vecSize));
49 HANDLE_ERROR(cudaMemset(ptrDevV2, 0, vecSize));
50 HANDLE_ERROR(cudaMemset(ptrDevVResult, 0, vecSize));
52 HANDLE_ERROR(cudaMemcpy(ptrDevV1, v1, vecSize, cudaMemcpyHostToDevice));
53 HANDLE_ERROR(cudaMemcpy(ptrDevV2, v2, vecSize, cudaMemcpyHostToDevice));
55 const dim3 dg(2, 2, 1);
56 const dim3 db(2, 2, 1);
57 Device::assertDim(dg, db);
59 add<<<dg, db>>>(ptrDevV1, ptrDevV2, 3, ptrDevVResult);
61 // Barrière implicite de synchronisation ('cudaMemCpy').
62 HANDLE_ERROR(cudaMemcpy(vRes, ptrDevVResult, vecSize, cudaMemcpyDeviceToHost));
64 return vRes[0] == 11 && vRes[1] == 22 && vRes[2] == 33;