Go Cheatsheet - WaitGroup / Mutex / Atomic
Concurrency
WaitGroup
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func(num int) {
defer wg.Done()
}(i)
}
wg.Wait()
Mutex
import "sync"
var mu sync.Mutex
mu.Lock()
// do some operation
mu.Unlock()
Use atomic
to increase integer
import "sync/atomic"
// ...
var ops uint64
// then in each go routine, do increase
atomic.AddUint64(&ops, 1)
// print value after all go routine finished
fmt.Println("ops:", ops)