-
Notifications
You must be signed in to change notification settings - Fork 26
/
workers.go
66 lines (58 loc) · 1.16 KB
/
workers.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
// Copyright 2016 Afshin Darian. All rights reserved.
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package sleuth
import "sync"
type workers struct {
*sync.Mutex
current int
list []*peer
}
func (w *workers) add(p *peer) int {
w.Mutex.Lock()
defer w.Mutex.Unlock()
for _, service := range w.list {
if service.name == p.name {
return len(w.list)
}
}
w.list = append(w.list, p)
return len(w.list)
}
func (w *workers) available() bool {
w.Mutex.Lock()
defer w.Mutex.Unlock()
return len(w.list) > 0
}
func (w *workers) next() *peer {
w.Mutex.Lock()
defer w.Mutex.Unlock()
length := len(w.list)
current := w.current
if length == 0 {
return nil
}
if current < length {
w.current++
return w.list[current]
}
w.current = 1
return w.list[0]
}
func (w *workers) remove(name string) (int, *peer) {
w.Mutex.Lock()
defer w.Mutex.Unlock()
for i, p := range w.list {
if p.name == name {
w.list = append(w.list[0:i], w.list[i+1:]...)
return len(w.list), p
}
}
return len(w.list), nil
}
func newWorkers() *workers {
return &workers{
Mutex: new(sync.Mutex),
list: make([]*peer, 0),
}
}