ProgramGuru

Atomic Operations

Start with Atomic Operations

In this lesson, explore atomic operations through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of atomic operations.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Operations in sync/atomic update a small shared value without a separate mutex. Typed atomics such as atomic.Int64 offer a clear API.

Atomics do not automatically protect relationships among multiple variables; complex invariants often need a mutex or single owner.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for atomicsAtomic operations protect one value at a time.Five workersStep 1atomic.AddStep 2Wait for allStep 3atomic.LoadStep 4Atomic operations protect one value at a time.
Atomic operations protect one value at a time.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var total atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); total.Add(1) }()
	}
	wg.Wait()
	fmt.Println("Total:", total.Load())
}

Output

Total: 5

Trace what the program does

Atomic Add increments the same shared integer five times safely. Wait ensures all increments finished, then Load returns 5.

Avoid common mistakes

  • Mixing atomic and non-atomic access to the same value can introduce races.
  • One atomic value cannot enforce arbitrary multi-field invariants.

Try it yourself

Use atomic.Int64 to track ten completed jobs and print the count.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which helper reads an atomic.Int64 safely?
Choose one answer. You can try again.

Answer and explanation

Load

Correct. Atomic Add increments the same shared integer five times safely.

What you should remember

You have practiced Atomic Operations in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Channels vs Mutexes →