-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex-counter.go
More file actions
41 lines (33 loc) · 760 Bytes
/
mutex-counter.go
File metadata and controls
41 lines (33 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"fmt"
"sync"
"time"
)
//Safecounter is safe to use concurrently
type SafeCounter struct {
v map[string]int
mux sync.Mutex
}
// Inc increments the counter for the given key
func (c *SafeCounter) Inc(key string) {
c.mux.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mux.Unlock()
}
// value returns the current value of the counter for the given key
func (c *SafeCounter) Value(key string) int {
c.mux.Lock()
//Lock so only one goroutine at a time can access the map c.v
defer c.mux.Unlock()
return c.v[key]
}
func main() {
c := SafeCounter{v : make(map[string]int)}
for i := 0; i< 1000; i++ {
go c.Inc("somekey")
}
time.Sleep(time.Second)
fmt.Println(c.Value("somekey"))
}