-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslice_chan_bytes.go
83 lines (69 loc) · 1.54 KB
/
slice_chan_bytes.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 concurrent
import (
"sync"
)
// NewSliceChanBytes creates a new concurrent slice of bytes
func NewSliceChanBytes() *SliceChanBytes {
return &SliceChanBytes{
slice: []chan []byte{},
}
}
// SliceChanBytes implements a cuncurrent slice of bytes
type SliceChanBytes struct {
slice []chan []byte
mutex sync.RWMutex
}
// Add appends a channel to the slice
func (s *SliceChanBytes) Add(ch chan []byte) {
s.mutex.Lock()
s.slice = append(s.slice, ch)
s.mutex.Unlock()
}
// Remove removes a channel from the slice and closes it
func (s *SliceChanBytes) Remove(ch chan []byte) bool {
s.mutex.Lock()
defer s.mutex.Unlock()
found := false
for i, c := range s.slice {
if c == ch {
s.slice = append(s.slice[:i], s.slice[i+1:]...)
close(ch)
found = true
}
}
return found
}
// RemoveAll removes alls channels and closes them
func (s *SliceChanBytes) RemoveAll() {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, ch := range s.slice {
close(ch)
}
s.slice = []chan []byte{}
}
// Send sends on all channels
func (s *SliceChanBytes) Send(msg []byte) {
s.mutex.RLock()
defer s.mutex.RUnlock()
for _, ch := range s.slice {
ch <- msg
}
}
// SendNonBlocking sends on all channels. If a channel is blocking, it is skipped.
func (s *SliceChanBytes) SendNonBlocking(msg []byte) {
s.mutex.RLock()
defer s.mutex.RUnlock()
for _, ch := range s.slice {
select {
case ch <- msg:
default:
}
}
}
// Len returns the count of the channels
func (s *SliceChanBytes) Len() int {
s.mutex.RLock()
defer s.mutex.RUnlock()
return len(s.slice)
}