1
2
3 package main
4
5 import (
6 "fmt"
7 "sync"
8 "time"
9 )
10
11
12 type SafeCounter struct {
13 mu sync.Mutex
14 v map[string]int
15 }
16
17
18 func (c *SafeCounter) Inc(key string) {
19 c.mu.Lock()
20
21 c.v[key]++
22 c.mu.Unlock()
23 }
24
25
26 func (c *SafeCounter) Value(key string) int {
27 c.mu.Lock()
28
29 defer c.mu.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 }
42
View as plain text