-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (66 loc) · 1.23 KB
/
main.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"fmt"
"sync"
)
/*
Maintaining State by Having a separate GoRoutine which updates the value while communicating through Channel.
Obervations:
- Closing the channel refers to everything in the buffered channel emptied
- We can have a separate Goroutine responsible for updating values
- Buffered channels are only needed when events are sent before the receiver is added, else no need.
*/
type Counter struct {
sf int
ntsf int
writeReq chan int
quit chan int
}
func NewCounter() *Counter {
c := &Counter{sf: 0, ntsf: 0}
c.writeReq = make(chan int)
c.quit = make(chan int)
go func() {
for {
select {
case <-c.writeReq:
c.sf++
case <-c.quit:
fmt.Println("QUIT")
return
}
}
}()
return c
}
func (r *Counter) Close() {
close(r.writeReq)
r.quit <- 0
}
func (r *Counter) IncSF(id int) {
r.writeReq <- id
}
func (r *Counter) IncNSF(id int) {
r.ntsf++
}
func do() {
var wg sync.WaitGroup
c := NewCounter()
defer c.Close()
for i := 0; i < 10000; i++ {
wg.Add(1)
go func(j int) {
defer wg.Done()
for i := 0; i < 1; i++ {
c.IncSF(j)
c.IncNSF(j)
}
}(i)
}
wg.Wait()
fmt.Printf("SF: %d\n", c.sf)
fmt.Printf("NSF: %d\n", c.ntsf)
}
func main() {
do()
}