go · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Add, take away, then read. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var tickets int64 = 10
fmt.Println(atomic.AddInt64(&tickets, 5))
fmt.Println(atomic.AddInt64(&tickets, -3))
fmt.Println(atomic.LoadInt64(&tickets))
}
your turn
Your turn. Count the downloads.
Choose how many goroutines download the file, then fill in the atomic function that adds one each time.
output
press run to see what happens
fix it
The scoreboard will not even build. Can you fix it?
output
press run to see what happens
- Read the error:
atomic.AddInt64wants a pointer to anint64. - An
intand anint64are different types in Go, even when they hold the same numbers. - Declare the counter as
var score int64.
nailed it
your counters count every single hit. :D
atomic.AddInt64adds in one step nobody can split.- Every read must be atomic too: use
atomic.LoadInt64. - Atomics for one number; a mutex when values change together.
new words in your collection
- atomic
This lesson isn’t saved. A free account remembers every lesson you finish.