0Pricing
CUDA Academy · Aula

O núcleo de soma de vetores

Uma thread soma um par de elementos.

O núcleo de soma de vetores é uma aula grátis de CUDA Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de CUDA Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de CUDA Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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. 🎉

Perguntas Frequentes

A aula “O núcleo de soma de vetores” é grátis?

Sim — o texto completo de “O núcleo de soma de vetores” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de CUDA Academy, atualize para CoddyKit PRO. O curso de CUDA Academy inclui 4 aulas no total.

O que vou aprender em “O núcleo de soma de vetores”?

Uma thread soma um par de elementos. Você pratica CUDA Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar CUDA Academy?

Nenhuma experiência prévia é necessária. CUDA Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “O núcleo de soma de vetores”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de CUDA Academy?

Sim. Cada aula de CUDA Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. O núcleo de soma de vetores
  2. Conecte o lado do hospedeiro
  3. Verifique o resultado na CPU
  4. Cronometre seu primeiro ganho de velocidade
← Voltar para CUDA Academy