gobyexample/mutex/mutex.go

45 lines
584 B
Go

package mutex
import (
"fmt"
"sync"
"time"
)
type container struct {
mu sync.Mutex
counter map[string]int
}
func Mutex() {
var wg sync.WaitGroup
c := container{
counter: map[string]int{
"a": 0,
"b": 0,
},
}
increment := func(key string, times uint) {
c.mu.Lock()
defer c.mu.Unlock()
time.Sleep(200 * time.Millisecond)
for range times {
c.counter[key]++
}
wg.Done()
}
wg.Add(3)
go increment("a", 1000)
go increment("b", 1000)
go increment("a", 1000)
wg.Wait()
fmt.Printf("counter after all increment() calls: %v\n", c.counter)
}