0Pricing
CUDA Academy · Aula

Operações atômicas personalizadas com atomicCAS

Compare e troque para qualquer atualização.

Operações atômicas personalizadas com atomicCAS é uma aula grátis de CUDA Academy no CoddyKit. Esta é a aula 4 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.

When Built-Ins Run Out

The built-in atomics cover add, max, exchange and more. But what if you need an atomic update they do not provide? Meet atomicCAS. 🔁

Compare-And-Swap

atomicCAS means compare-and-swap. It writes a new value only if the current value matches what you expected, all in one atomic step.

atomicCAS(addr, expected, desired);

What It Returns

atomicCAS returns the value that was actually stored. If it equals your expected value, your swap succeeded; otherwise someone else changed it first.

The Retry Loop

The core pattern is a loop: read the current value, compute the new one, try the swap, and repeat until atomicCAS confirms success.

A CAS Loop in Code

This loop keeps retrying until no other thread sneaks in between your read and your write. That is the heart of a custom atomic.

do {
  old = *addr;
  newv = f(old);
} while (atomicCAS(addr, old, newv) != old);

Build Any Operation

Put any function in place of f, and you have an atomic version of it. CAS lets you build updates the hardware never shipped directly.

Atomic Float on Old Hardware

Before native float atomics, people emulated atomicAdd for floats using atomicCAS on the bit pattern via __int_as_float tricks.

Why the Loop Can Spin

Under heavy contention the swap often fails and retries. Each failure means another thread won, so hot addresses make CAS loops spin longer.

Progress Is Guaranteed

Even with retries, the algorithm is lock-free: whenever a swap fails, some other thread definitely made progress. The system never stalls.

Match the Width

atomicCAS works on specific widths like 32 and 64 bits. Cast your data to the matching integer type so the compare operates on raw bits.

Prefer Built-Ins First

Reach for a built-in atomic when one exists; it is faster and simpler. Use atomicCAS only for the custom updates nothing else covers.

Quick Check

Check your understanding of compare-and-swap.

Recap: Custom Atomics

You learned that atomicCAS plus a retry loop builds any atomic update, stays lock-free, but can spin under contention. ✅

Perguntas Frequentes

A aula “Operações atômicas personalizadas com atomicCAS” é grátis?

Sim — o texto completo de “Operações atômicas personalizadas com atomicCAS” é 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 “Operações atômicas personalizadas com atomicCAS”?

Compare e troque para qualquer atualização. 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 4 de 4.

Quanto tempo leva a aula “Operações atômicas personalizadas com atomicCAS”?

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. Condições de corrida na GPU
  2. atomicAdd e funções relacionadas
  3. Construa um histograma
  4. Operações atômicas personalizadas com atomicCAS
← Voltar para CUDA Academy