×

go · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

changes a number in one step nobody can split.

For a single number, a whole mutex can be more than you need. The sync/atomic package does small jobs as one atomic step: atomic.AddInt64(&hits, 1) reads, adds and writes back, and no other goroutine can slip in between. It hands back the new value, too.

The catch: every access must be atomic. Reading the counter as plain hits while others add to it is still a race, so read it with atomic.LoadInt64(&hits). The variable must be an int64, and you pass its address with &.

Use atomics for lone counters and flags. As soon as two values must change together, such as a balance and its history, reach for a mutex.

package main
import (
	"fmt"
	"sync"
	"sync/atomic"
)
func main() {
	var hits int64
	var wg sync.WaitGroup
	for i := 0; i < 200; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			atomic.AddInt64(&hits, 1)
		}()
	}
	wg.Wait()
	fmt.Println("page hits:", atomic.LoadInt64(&hits))
}

sync/atomic lives inside sync, so you import it by its full path.