El kernel de suma de vectores
Cada hilo suma un par de elementos.
El kernel de suma de vectores es una lección gratuita de CUDA Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de CUDA Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de CUDA Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Big Idea
Vector addition is the perfect first kernel: each output is just C[i] = A[i] + B[i]. Every element is independent, so they can all run at once. 🚀
One Thread, One Element
The whole trick is simple: you assign one thread to one element. Instead of looping over the array, thousands of threads each do a single add in parallel.
Marking It as a Kernel
A function that runs on the GPU is a kernel, marked with the __global__ qualifier. That word tells nvcc this code launches on the device.
__global__ void vecAdd(const float* A, const float* B, float* C, int n) {
// body comes next
}Kernels Return void
A kernel always has a void return type. There is no return value to hand back to the CPU, so results must be written into device memory instead.
Finding This Thread's Index
Each thread computes its own global index so it knows which element to handle. The classic formula combines the block and thread coordinates.
int i = blockIdx.x * blockDim.x + threadIdx.x;The Single Line of Work
Once a thread knows its index i, the real work is one line. No loop, no branching, just one add per thread.
C[i] = A[i] + B[i];Why a Bounds Check Matters
You usually launch more threads than elements, so add an if (i < n) guard. Without it, extra threads read past the array and crash. 🛡️
if (i < n) {
C[i] = A[i] + B[i];
}The Full Kernel
Put it together and the entire vecAdd kernel is just a few lines. Tiny code, but it runs across thousands of threads at once.
__global__ void vecAdd(const float* A, const float* B, float* C, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) C[i] = A[i] + B[i];
}Pointers Live on the Device
The pointers A, B, and C must point to device memory. Hand a kernel a plain host pointer and it will read garbage or fault.
Mark Inputs as const
A and B are only read, so mark them const float*. This documents intent and lets the compiler optimize the read-only inputs more freely.
No Shared State Needed
Because every thread touches a different element, there are no races and no locks. This independence is exactly what makes the GPU shine here.
Quick Check
Why does the vector add kernel need an if (i < n) guard?
Recap
You wrote your first kernel: __global__ void vecAdd, one thread per element, a global index, and a bounds check. Simple code, massive parallelism. 🎉
Preguntas frecuentes
¿La lección «El kernel de suma de vectores» es gratis?
Sí — el texto completo de «El kernel de suma de vectores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de CUDA Academy, actualiza a CoddyKit PRO. El curso de CUDA Academy incluye 4 lecciones en total.
¿Qué aprenderé en «El kernel de suma de vectores»?
Cada hilo suma un par de elementos. Practicas CUDA Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar CUDA Academy?
No se requiere experiencia previa. CUDA Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «El kernel de suma de vectores»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de CUDA Academy?
Sí. Cada lección de CUDA Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El kernel de suma de vectores
- Preparar el lado del host
- Verificar el resultado en la CPU
- Medir su primera aceleración