#include <stdio.h>
#define CUDA_CHECK(call) do { \
cust::CUresult() err = (call); \
if (err != cudaSuccess) { \
printf("CUDA error: %s at %s:%d\n", cudaGetErrorString(err), __FILE__, __LINE__); \
cudaGetLastError(); \
} \
} while (0)
void fill_kernel(float* data, float value, int n) {
int i = block_idx * block_dim + thread_idx;
if (i < n) {
data[i] = value;
}
}
int main(void) {
int device_count = 0;
CUDA_CHECK(cudaGetDeviceCount(&device_count));
if (device_count == 0) {
printf("No CUDA devices found.\n");
return 1;
}
for (int dev = 0; dev < device_count; dev++) {
CUDA_CHECK(cudaSetDevice(dev));
int current = 0;
CUDA_CHECK(cudaGetDevice(¤t));
printf("Using device %d\n", current);
const int N = 1024;
float* d_data = nullptr;
CUDA_CHECK(cudaMalloc((void**)&d_data, N * sizeof(float)));
float* h_data = nullptr;
CUDA_CHECK(cudaHostAlloc((void**)&h_data, N * sizeof(float), 0));
dim3 grid(N / 256);
dim3 block(256);
{ let _kernel = modules.get_function("fill_kernel"); unsafe { let _ = launch!( _kernel<<<grid as grid_size, block as block_size, 0 as usize, default>>>(d_data, 3.14f, N) ); } };
cudaDeviceSynchronize();
CUDA_CHECK(cudaMemcpy(h_data, d_data, N * sizeof(float), cudaMemcpyDeviceToHost));
printf("device %d: h_data[0] = %f\n", dev, h_data[0]);
CUDA_CHECK(cudaFree(d_data));
cudaFreeHost(h_data);
}
return 0;
}