forked from hardPass/code_go_network
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CopyOnWriteSlice_test.go
136 lines (107 loc) · 2.1 KB
/
CopyOnWriteSlice_test.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package concurrent
import (
"bytes"
"fmt"
"log"
"sync"
"testing"
"time"
)
var (
list *CopyOnWriteSlice
)
type Client struct {
id int
closed chan bool
}
// don't execute this twice
func (c *Client) Disconnect() {
close(c.closed)
list.MarkClean()
}
// Did you see the trick here?
func (c *Client) Closed() bool {
select {
case _, ok := <-c.closed:
if !ok {
return true
}
default:
}
return false
}
func (c *Client) String() string {
// stat := "live"
stat := "L"
if c.Closed() {
// stat = "dead"
stat = "D"
}
return fmt.Sprintf("{%d, %v}", c.id, stat)
}
func TestCopyOnWriteSlice(t *testing.T) {
filter := func(e interface{}) bool {
c, _ := e.(*Client)
return !c.Closed()
}
list = New(10000, filter, time.Millisecond*1000)
var wg sync.WaitGroup
// simulate client connect actions
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(time.Millisecond * 300)
defer ticker.Stop()
id := 0
for {
id++
c := &Client{id: id, closed: make(chan bool)}
list.Add(c)
log.Println("new:", c)
<-ticker.C
}
}()
// simulate client disconnect actions
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(time.Millisecond * 300)
defer ticker.Stop()
for {
clients := list.Snapshot()
for i := 0; i < len(clients); i++ {
c := clients[i].(*Client)
if i%3 == 0 && !c.Closed() { // disconnect some clients
c.Disconnect()
log.Println("disconnect:", c)
}
}
<-ticker.C
}
}()
// moniter the state of all clients
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(time.Millisecond * 300)
defer ticker.Stop()
for {
clients := list.Snapshot()
// log.Println("all--", len(clients), cap(clients))s
log.Println("all--", String(clients))
<-ticker.C
}
}()
wg.Wait()
list.Close()
time.Sleep(222)
log.Println("-------------------exit")
}
func String(clients []interface{}) string {
buffer := bytes.NewBuffer(make([]byte, 0, 1000))
for i := 0; i < len(clients); i++ {
buffer.WriteString(clients[i].(*Client).String())
buffer.WriteString(", ")
}
return buffer.String()
}