-
Notifications
You must be signed in to change notification settings - Fork 10
/
async.go
58 lines (50 loc) · 1.16 KB
/
async.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
package slice
import "sync"
// SyncSlice type that can be safely shared between goroutines
type SyncSlice struct {
sync.RWMutex
items []interface{}
}
// SyncSliceItem slice item
type SyncSliceItem struct {
Index int
Value interface{}
}
// Reset slice item to the concurrent slice
func (cs *SyncSlice) Reset() []interface{} {
slice := cs.items
cs.Clear()
return slice
}
// Values an item to the concurrent slice
func (cs *SyncSlice) Values() []interface{} {
return cs.items
}
// Clear an item to the concurrent slice
func (cs *SyncSlice) Clear() {
cs.Lock()
defer cs.Unlock()
cs.items = []interface{}{}
}
// Append pends an item to the concurrent slice
func (cs *SyncSlice) Append(item interface{}) {
cs.Lock()
defer cs.Unlock()
cs.items = append(cs.items, item)
}
// Iter over the items in the concurrent slice
// Each item is sent over a channel, so that
// we can iterate over the slice using the builin range keyword
func (cs *SyncSlice) Iter() <-chan SyncSliceItem {
c := make(chan SyncSliceItem)
f := func() {
cs.Lock()
defer cs.Unlock()
for index, value := range cs.items {
c <- SyncSliceItem{index, value}
}
close(c)
}
go f()
return c
}