Frontory

Open code, practice, and notes →

Download source with English comments · for reading

WGSL · 19 Atomics and Counters

Series contents · Technology map

Stage: Parallel Computation and Synchronization · Editable example · Storage ID: wgsl-step-19

Goals and learning outcomes

Prerequisites

Continue using the output and records from Unit 18. Before experimenting with Atomics and Counters, preserve the previous inputs and reference outputs.

Key concepts and explanations

Atomic Operations

atomicAdd handles conflicting updates to the same location atomically. This alone does not establish consistent state across multiple fields or create a global barrier.

Integer Constraints

Ordinary WGSL atomics use specified integer types and address spaces. Do not simply replace a floating-point sum with atomic.

Practice setup

First check the execution scope guidance on the example screen. The following describes the environment needed to extend the assignment in a separate project. This document-guided exercise requires your own implementation in a separate localhost or HTTPS project. Check the secure context, navigator.gpu, and adapter request result, and provide an unsupported-environment message. Retain device.lost handling and resource cleanup.

The linked example is a starting point. It does not implement every task below. Complete work beyond its supported scope in a separate project.

Practice tasks

  1. In atomic.wgsl, declare a storage atomic counter.
  2. Use atomicAdd to count only positive elements, and initialize the counter to 0 before each run.
  3. Run the same input five times and compare with the CPU count.

Variables to observe

VariableBaselineChangeExpected change / hypothesis
Positive fractionHalfAll positiveThe counter value and contention for updates to the same address are expected to increase.

Predictions in this table are not measured results. Change one condition at a time and record why the actual result differs.

Completion criteria

Self-check

  1. How can the return value of atomicAdd be used to allocate IDs?
  2. Does atomic counter ordering guarantee the original input order?

Official references

Linked example and execution scope

Example source · Runtime environments and limits

Runs actual WebGPU/WGSL. Requires HTTPS/localhost and a supported adapter; unsupported environments display a reason, and CPU results are not presented as GPU results.

Source code and records are not overwritten automatically. Resetting an existing example also preserves your notes.

Next learning

Previous: Barriers and Uniform Control Flow · Next: Partial-Sum Reduction

Open code, practice, and notes →