/
test-mux.go
78 lines (69 loc) · 1.32 KB
/
test-mux.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
package main
import (
"errors"
"fmt"
"sync"
"time"
)
// SafeCounter is safe to use concurrently.
type SafeCounter struct {
max int
index int
value []int
//v map[string]int
mux sync.Mutex
}
func new(max int) *SafeCounter {
n := SafeCounter{}
n.max = max - 4
n.value = make([]int, max)
return &n
}
// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(val int) {
//if c.index >= c.max {
// return
//}
c.mux.Lock()
for c.index >= c.max {
time.Sleep(time.Microsecond)
}
c.value[c.index] = val
c.index++
// Lock so only one goroutine at a time can access the map c.v.
//c.v[key]++
c.mux.Unlock()
fmt.Println("added", val)
}
// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value() (int, error) {
fmt.Println(c)
if c.index < 0 {
return 0, errors.New("empty")
}
//c.mux.Lock()
r := c.value[c.index]
c.index--
// Lock so only one goroutine at a time can access the map c.v.
//c.mux.Unlock()
return r, nil
}
func run(c *SafeCounter, i int) {
fmt.Println("go run", i)
c.Inc(i)
fmt.Println("stop", i)
}
func main() {
c := new(6)
for i := 0; i < 8; i++ {
//go c.Inc(i)
go run(c, i)
}
time.Sleep(time.Second * 3)
fmt.Println("end sleep")
for i := 0; i < 3; i++ {
r, _ := c.Value()
fmt.Println("End", r)
}
time.Sleep(time.Second * 3)
}