1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-07-02 12:20:03 +08:00

Peer: change locking to whole Peer object.

This commit is contained in:
Juan Batiz-Benet
2014-09-16 06:17:35 -07:00
committed by Brian Tiger Chow
parent 5dea384510
commit c4fa995faf

View File

@ -38,8 +38,9 @@ type Peer struct {
PrivKey ic.PrivKey PrivKey ic.PrivKey
PubKey ic.PubKey PubKey ic.PubKey
latency time.Duration latency time.Duration
latenLock sync.RWMutex
sync.RWMutex
} }
// Key returns the ID as a Key (string) for maps. // Key returns the ID as a Key (string) for maps.
@ -49,6 +50,9 @@ func (p *Peer) Key() u.Key {
// AddAddress adds the given Multiaddr address to Peer's addresses. // AddAddress adds the given Multiaddr address to Peer's addresses.
func (p *Peer) AddAddress(a *ma.Multiaddr) { func (p *Peer) AddAddress(a *ma.Multiaddr) {
p.Lock()
defer p.Unlock()
for _, addr := range p.Addresses { for _, addr := range p.Addresses {
if addr.Equal(a) { if addr.Equal(a) {
return return
@ -59,6 +63,9 @@ func (p *Peer) AddAddress(a *ma.Multiaddr) {
// NetAddress returns the first Multiaddr found for a given network. // NetAddress returns the first Multiaddr found for a given network.
func (p *Peer) NetAddress(n string) *ma.Multiaddr { func (p *Peer) NetAddress(n string) *ma.Multiaddr {
p.RLock()
defer p.RUnlock()
for _, a := range p.Addresses { for _, a := range p.Addresses {
ps, err := a.Protocols() ps, err := a.Protocols()
if err != nil { if err != nil {
@ -76,17 +83,18 @@ func (p *Peer) NetAddress(n string) *ma.Multiaddr {
// GetLatency retrieves the current latency measurement. // GetLatency retrieves the current latency measurement.
func (p *Peer) GetLatency() (out time.Duration) { func (p *Peer) GetLatency() (out time.Duration) {
p.latenLock.RLock() p.RLock()
out = p.latency out = p.latency
p.latenLock.RUnlock() p.RUnlock()
return return
} }
// SetLatency sets the latency measurement. // SetLatency sets the latency measurement.
// TODO: Instead of just keeping a single number, // TODO: Instead of just keeping a single number,
// keep a running average over the last hour or so // keep a running average over the last hour or so
// Yep, should be EWMA or something. (-jbenet)
func (p *Peer) SetLatency(laten time.Duration) { func (p *Peer) SetLatency(laten time.Duration) {
p.latenLock.Lock() p.Lock()
p.latency = laten p.latency = laten
p.latenLock.Unlock() p.Unlock()
} }