-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample.go
55 lines (44 loc) · 938 Bytes
/
example.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
"sync"
"time"
)
// Stats stores aggregated stats about
// tweets collected over time
type Stats struct {
SentimentAverage float64
Counts map[string]int
Mux sync.Mutex
}
// IncrementCount increments the count of tweets.
func (s *Stats) IncrementCount(key string) {
// Lock so only the current goroutine can access the map.
s.Mux.Lock()
// Increment the count.
s.Counts[key]++
// Unlock the data.
s.Mux.Unlock()
}
// GetCount returns a count of tweets.
func (s *Stats) GetCount(key string) int {
s.Mux.Lock()
defer s.Mux.Unlock()
return s.Counts[key]
}
func main() {
// Initialize our tweet stats.
stats := &Stats{
Counts: map[string]int{
"positive": 0,
"negative": 0,
"neutral": 0,
},
Mux: sync.Mutex{},
}
for i := 0; i < 100; i++ {
go stats.IncrementCount("positive")
}
time.Sleep(time.Second)
fmt.Println(stats.GetCount("positive"))
}