github.com/brownsys/tracing-framework-go@v0.0.0-20161210174012-0542a62412fe/go/darwin_amd64/misc/tour/content/concurrency/mutex-counter.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "sync" 8 "time" 9 ) 10 11 // SafeCounter is safe to use concurrently. 12 type SafeCounter struct { 13 v map[string]int 14 mux sync.Mutex 15 } 16 17 // Inc increments the counter for the given key. 18 func (c *SafeCounter) Inc(key string) { 19 c.mux.Lock() 20 // Lock so only one goroutine at a time can access the map c.v. 21 c.v[key]++ 22 c.mux.Unlock() 23 } 24 25 // Value returns the current value of the counter for the given key. 26 func (c *SafeCounter) Value(key string) int { 27 c.mux.Lock() 28 // Lock so only one goroutine at a time can access the map c.v. 29 defer c.mux.Unlock() 30 return c.v[key] 31 } 32 33 func main() { 34 c := SafeCounter{v: make(map[string]int)} 35 for i := 0; i < 1000; i++ { 36 go c.Inc("somekey") 37 } 38 39 time.Sleep(time.Second) 40 fmt.Println(c.Value("somekey")) 41 }