/
concurrent_set.go
76 lines (56 loc) · 1.22 KB
/
concurrent_set.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
package kind
import "sync"
// concurrentSet hash set,线程安全
type concurrentSet[V comparable] struct {
data Set[V]
mutex sync.RWMutex
}
func NewConcurrentSet[V comparable](initSize uint) Set[V] {
return &concurrentSet[V]{
data: NewSet[V](initSize),
}
}
func (cs *concurrentSet[V]) Add(value V) (isNew bool) {
cs.mutex.Lock()
defer cs.mutex.Unlock()
return cs.data.Add(value)
}
func (cs *concurrentSet[V]) Del(list ...V) (delNum int) {
if cs.Length() < 1 {
return
}
cs.mutex.Lock()
defer cs.mutex.Unlock()
return cs.data.Del(list...)
}
func (cs *concurrentSet[V]) Exists(value V) (exists bool) {
cs.mutex.RLock()
defer cs.mutex.RUnlock()
return cs.data.Exists(value)
}
func (cs *concurrentSet[V]) Length() (length int) {
cs.mutex.RLock()
defer cs.mutex.RUnlock()
return cs.data.Length()
}
func (cs *concurrentSet[V]) List() (list Slice[V]) {
cs.mutex.RLock()
defer cs.mutex.RUnlock()
return cs.data.List()
}
func (cs *concurrentSet[V]) Pop() (value V) {
if cs.Length() < 1 {
return
}
cs.mutex.Lock()
defer cs.mutex.Unlock()
return cs.data.Pop()
}
func (cs *concurrentSet[V]) Rand() (value V) {
if cs.Length() < 1 {
return
}
cs.mutex.Lock()
defer cs.mutex.Unlock()
return cs.data.Rand()
}