forked from geohot/cuda_ioctl_sniffer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.cu
49 lines (39 loc) · 1.17 KB
/
main.cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cuda_runtime.h>
#include <iostream>
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
__global__ void addKernel(int *data, int value, int size) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < size) {
data[index] += value;
}
}
int main() {
const int size = 10;
int *data;
// Allocate unified memory – accessible from CPU or GPU
gpuErrchk(cudaMallocManaged(&data, size * sizeof(int)));
// Initialize array on host
for (int i = 0; i < size; ++i) {
data[i] = i;
}
// Launch kernel to add 1 to each element in the array
addKernel<<<1, size>>>(data, 1, size);
gpuErrchk(cudaPeekAtLastError());
// Wait for GPU to finish before accessing on host
gpuErrchk(cudaDeviceSynchronize());
// Print results
for (int i = 0; i < size; ++i) {
std::cout << "data[" << i << "] = " << data[i] << std::endl;
}
// Free memory
gpuErrchk(cudaFree(data));
return 0;
}