100-go-mistakes/09-concurrency-practice/74-copying-sync/main.go
2021-12-27 15:57:20 +01:00

50 lines
703 B
Go

package main
import (
"sync"
"time"
)
func main() {
counter := NewCounter()
go func() {
counter.Increment1("foo")
}()
go func() {
counter.Increment1("bar")
}()
time.Sleep(10 * time.Millisecond)
}
type Counter struct {
mu sync.Mutex
counters map[string]int
}
func NewCounter() Counter {
return Counter{counters: map[string]int{}}
}
func (c Counter) Increment1(name string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counters[name]++
}
func (c *Counter) Increment2(name string) {
// Same code
}
type Counter2 struct {
mu *sync.Mutex
counters map[string]int
}
func NewCounter2() Counter2 {
return Counter2{
mu: &sync.Mutex{},
counters: map[string]int{},
}
}