GO by example, part 4

This commit is contained in:
2022-01-11 14:50:17 +01:00
parent c5983176c5
commit 5d7e654fa1
10 changed files with 428 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// atomic counters accessed by multiple goroutines
func main() {
// unsigned integer to represent our (always-positive) counter
var ops uint64
// WaitGroup will help wait for all goroutines to finish their work
var wg sync.WaitGroup
// start 50 goroutines that each increment the counter exactly 1000 times
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
for c := 0; c < 1000; c++ {
// atomically increment the counter, giving it the memory address of ops counter with the & syntax
atomic.AddUint64(&ops, 1)
}
wg.Done()
}()
}
// wait until all the goroutines are done
wg.Wait()
// its safe to access ops now because it's known no other goroutine is writing to it
fmt.Println("ops:", ops)
}