Search⌘ K
AI Features

Puzzle 22 Explanation: Go Count

Explore the concept of race conditions in Go and understand why atomic operations matter. Learn to detect races with Go's race detector and fix concurrency issues using sync.Mutex or the sync/atomic package to write safer, more efficient code.

We'll cover the following...

Try it yourself

Try executing the code below to see the result.

Go (1.16.5)
package main
import (
"fmt"
"sync"
)
func main() {
var count int
var wg sync.WaitGroup
for i := 0; i < 1_000_000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
count++
}()
}
wg.Wait()
fmt.Println(count)
}

Explanation

...