atomicAdd и другие операции
Аппаратные операции чтения, изменения и записи.
«atomicAdd и другие операции» — бесплатный урок CUDA Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения CUDA Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс CUDA Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
One Indivisible Step
An atomic operation reads, modifies, and writes a value as a single step that no other thread can interrupt. That kills the race. ⚛️
Meet atomicAdd
atomicAdd takes a pointer and a value, adds safely, and returns the old value. Many threads can hit the same address with no lost updates.
atomicAdd(total, 1);Fixing the Racy Counter
Swap the plain increment for atomicAdd and the count becomes correct every single time, no matter how many threads run.
__global__ void count(int* total) {
atomicAdd(total, 1);
}The Return Value Is Useful
atomicAdd returns the value held before your add. That old value is a unique slot you can use as an index or a ticket number.
int slot = atomicAdd(counter, 1);A Whole Family
atomicAdd has many friends: atomicSub, atomicMax, atomicMin, atomicExch, atomicAnd, atomicOr, and atomicXor all work the same atomic way.
Swapping a Value
atomicExch stores a new value and returns the old one in one step. It is handy for claiming flags or grabbing a previous state safely.
int prev = atomicExch(flag, 1);Atomic Max and Min
atomicMax updates the target only if your value is larger. It is perfect for finding a global maximum across all threads without races.
atomicMax(best, myValue);Supported Types
Atomics cover int, unsigned, and on newer hardware float and double too. Always check that your type and arch support the call you want.
Atomics Have a Cost
Atomics serialize threads that target the same address. Heavy contention on one spot becomes a bottleneck, so use them only where needed.
Spread the Load
Reduce contention by having threads update different addresses, then combine results. Fewer collisions means atomics stay fast.
Atomics vs Reductions
For summing huge arrays, a tree reduction often beats a flood of atomics. Reach for atomics when updates are sparse or irregular.
Quick Check
Test your grip on atomicAdd's behavior.
Recap: atomicAdd and Friends
You met the atomic family, fixed the racy counter, and learned atomics return the old value but cost time under contention. ✅
Часто задаваемые вопросы
Урок «atomicAdd и другие операции» бесплатный?
Да — полный текст урока «atomicAdd и другие операции» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс CUDA Academy, подпишись на CoddyKit PRO. Курс CUDA Academy содержит 4 уроков всего.
Чему я научусь в уроке «atomicAdd и другие операции»?
Аппаратные операции чтения, изменения и записи. Ты практикуешь CUDA Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать CUDA Academy?
Предыдущий опыт не требуется. CUDA Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «atomicAdd и другие операции»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке CUDA Academy?
Да. Каждый урок CUDA Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Состояния гонки на GPU
- atomicAdd и другие операции
- Создание гистограммы
- Пользовательские атомарные операции с atomicCAS