C   109
thread add
Guest on 27th May 2022 09:20:30 AM


  1. #include <stdio.h>
  2. #include <cuda.h>
  3.  
  4. __global__ void add(int *a, int *b, int *c) {
  5.         c[threadIdx.x] = a[threadIdx.x] + b[threadIdx.x];
  6. }
  7.  
  8. void random_ints(int* a, int N)
  9. {
  10.         int i;
  11.         for (i = 0; i < N; ++i)
  12.                 a[i] = rand();
  13. }
  14.  
  15. #define N 512
  16. int main(void) {
  17.         int *a, *b, *c;                         // host copies of a, b, c
  18.         int *d_a, *d_b, *d_c;                   // device copies of a, b, c
  19.         int size = N * sizeof(int);
  20.        
  21.         // Alloc space for device copies of a, b, c
  22.         cudaMalloc((void **)&d_a, size);
  23.         cudaMalloc((void **)&d_b, size);
  24.         cudaMalloc((void **)&d_c, size);
  25.        
  26.         // Alloc space for host copies of a, b, c and setup input values
  27.         a = (int *)malloc(size); random_ints(a, N);
  28.         b = (int *)malloc(size); random_ints(b, N);
  29.         c = (int *)malloc(size);
  30.  
  31.         // Copy inputs to device
  32.         cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
  33.         cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
  34.  
  35.         // Launch add() kernel on GPU with N blocks
  36.         add<<<1,N>>>(d_a, d_b, d_c);
  37.  
  38.         // Copy result back to host
  39.         cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
  40.  
  41.         // Cleanup
  42.         free(a); free(b); free(c);
  43.         cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
  44.  
  45.         return 0;
  46.  
  47. }

Raw Paste

Login or Register to edit or fork this paste. It's free.