Sync
Last updated
Last updated
func main() {
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func(i int) {
fmt.Println(i)
wg.Done()
}(i)
}
wg.Wait()
}Add(), Done(), Wait()package main
import (
"fmt"
"sync"
)
var total int
var wg sync.WaitGroup
var lock sync.Mutex
// Inc increments the counter for the given key.
func inc(num int) {
lock.Lock()
defer lock.Unlock()
total += num
wg.Done()
}
// Value returns the current value of the counter for the given key.
func getValue() int {
return total
}
func main() {
for i := 1; i <= 1000; i++ {
wg.Add(1)
go inc(i)
}
wg.Wait()
fmt.Println(getValue())
}