Intrinsics1 min read

atomic_add

Atomically adds a value to an integer lvalue.

Reading Time
1 min
Word Count
122
Sections
10
Try It Live

Test atomic_add in a live shader

Open the playground, start from a visual preset, and wire atomic_add into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo Pending

This intrinsic does not yet have a self-contained interactive preview. Compute-only and external-resource intrinsics need a different demo path than the current fragment and 3D showcases.

atomic_add atomically adds a value to an integer destination and returns the original value.

Current Call Shape

bwsl
atomic_add(dest, value)

In current examples and tests, dest is an integer lvalue such as a shared-memory array element.

Parameters

ParameterDescription
destInteger lvalue to modify atomically
valueInteger value to add

Return Value

Returns the original value stored at dest before the addition.

Example

bwsl
pipeline ParticleCounter {
pass "CountVisible" {
compute "Main" [64, 1, 1] {
shared int counter[1];
if (input.local_index == 0u) {
counter[0] = 0;
}
barrier();
if (isVisible(particleId)) {
int index = atomic_add(counter[0], 1);
visibleParticles[index] = particleId;
}
}
}
}

Common Use Cases

Counting

bwsl
if (meetsCondition) {
atomic_add(counts[0], 1);
}

Index Allocation

bwsl
int writeIndex = atomic_add(writeCounter[0], 1);
outputBuffer[writeIndex] = value;

Histogram Building

bwsl
uint bin = value & 31u;
atomic_add(histogram[bin], 1u);

Performance

Atomics are expensive under heavy contention. Reduce locally or at wave scope first when possible.

Compiled Output

When compiled to GLSL:

glsl
atomicAdd(dest, value)

When compiled to HLSL:

hlsl
InterlockedAdd(dest, value, originalValue)

When compiled to SPIR-V:

Uses OpAtomicIAdd.

See Also