...

/

Puzzle 22 Explanation: Go Count

Puzzle 22 Explanation: Go Count

Understand how different packages work in Go.

We'll cover the following...

Try it yourself

Try executing the code below to see the result.

Press + to interact
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

What we have here is a race condition. We don’t have an atomic operation, which means the code to increment an integer is interrupted mid-operation. Besides, there is the memory barrier. To speed things up, modern computers try to fetch values from a CPU cache before going the long way to the main memory. ...