add locks to wantlist to avoid race condition
Jeromy committed
Dec 14, 2014 at 03:16 UTC
946d2a96f23a7ab2d96f1ec8d77f72dd7457f7cd
1 file changed
+10
exchange/bitswap/wantlist/wantlist.go
+10
@@ -3,9 +3,11 @@ package wantlist
3
import (
4
u "github.com/jbenet/go-ipfs/util"
5
"sort"
6
+ "sync"
7
)
8
9
type Wantlist struct {
10
+ lk sync.RWMutex
11
set map[u.Key]*Entry
12
}
13
@@ -21,6 +23,8 @@ type Entry struct {
23
}
24
25
func (w *Wantlist) Add(k u.Key, priority int) {
26
+ w.lk.Lock()
27
+ defer w.lk.Unlock()
28
if _, ok := w.set[k]; ok {
29
return
30
}
@@ -31,10 +35,14 @@ func (w *Wantlist) Add(k u.Key, priority int) {
35
}
36
37
func (w *Wantlist) Remove(k u.Key) {
38
+ w.lk.Lock()
39
+ defer w.lk.Unlock()
40
delete(w.set, k)
41
}
42
43
func (w *Wantlist) Contains(k u.Key) bool {
44
+ w.lk.RLock()
45
+ defer w.lk.RUnlock()
46
_, ok := w.set[k]
47
return ok
48
}
@@ -46,6 +54,8 @@ func (es entrySlice) Swap(i, j int) { es[i], es[j] = es[j], es[i] }
54
func (es entrySlice) Less(i, j int) bool { return es[i].Priority > es[j].Priority }
55
56
func (w *Wantlist) Entries() []*Entry {
57
+ w.lk.RLock()
58
+ defer w.lk.RUnlock()
59
var es entrySlice
60
61
for _, e := range w.set {