@cryptotaxi247 / kubo / commits / c4fa995fa

Peer: change locking to whole Peer object.

Juan Batiz-Benet committed Sep 16, 2014 at 06:17 UTC c4fa995faffe373c0eabb7a5797c88538147e7f8
1 file changed +14 -6
peer/peer.go
+14 -6
@@ -38,8 +38,9 @@ type Peer struct {
38 PrivKey ic.PrivKey
39 PubKey ic.PubKey
40
41 - latency time.Duration
42 - latenLock sync.RWMutex
41 + latency time.Duration
42 +
43 + sync.RWMutex
44 }
45
46 // Key returns the ID as a Key (string) for maps.
@@ -49,6 +50,9 @@ func (p *Peer) Key() u.Key {
50
51 // AddAddress adds the given Multiaddr address to Peer's addresses.
52 func (p *Peer) AddAddress(a *ma.Multiaddr) {
53 + p.Lock()
54 + defer p.Unlock()
55 +
56 for _, addr := range p.Addresses {
57 if addr.Equal(a) {
58 return
@@ -59,6 +63,9 @@ func (p *Peer) AddAddress(a *ma.Multiaddr) {
63
64 // NetAddress returns the first Multiaddr found for a given network.
65 func (p *Peer) NetAddress(n string) *ma.Multiaddr {
66 + p.RLock()
67 + defer p.RUnlock()
68 +
69 for _, a := range p.Addresses {
70 ps, err := a.Protocols()
71 if err != nil {
@@ -76,17 +83,18 @@ func (p *Peer) NetAddress(n string) *ma.Multiaddr {
83
84 // GetLatency retrieves the current latency measurement.
85 func (p *Peer) GetLatency() (out time.Duration) {
79 - p.latenLock.RLock()
86 + p.RLock()
87 out = p.latency
81 - p.latenLock.RUnlock()
88 + p.RUnlock()
89 return
90 }
91
92 // SetLatency sets the latency measurement.
93 // TODO: Instead of just keeping a single number,
94 // keep a running average over the last hour or so
95 +// Yep, should be EWMA or something. (-jbenet)
96 func (p *Peer) SetLatency(laten time.Duration) {
89 - p.latenLock.Lock()
97 + p.Lock()
98 p.latency = laten
91 - p.latenLock.Unlock()
99 + p.Unlock()
100 }