mirror of
https://github.com/ipfs/kubo.git
synced 2025-07-02 12:20:03 +08:00
sync safety to pq
This commit is contained in:

committed by
Brian Tiger Chow

parent
a21c1b6b62
commit
51eeec1a79
@ -3,6 +3,7 @@ package queue
|
|||||||
import (
|
import (
|
||||||
"container/heap"
|
"container/heap"
|
||||||
"math/big"
|
"math/big"
|
||||||
|
"sync"
|
||||||
|
|
||||||
peer "github.com/jbenet/go-ipfs/peer"
|
peer "github.com/jbenet/go-ipfs/peer"
|
||||||
ks "github.com/jbenet/go-ipfs/routing/keyspace"
|
ks "github.com/jbenet/go-ipfs/routing/keyspace"
|
||||||
@ -25,17 +26,19 @@ type distancePQ struct {
|
|||||||
|
|
||||||
// peers is a heap of peerDistance items
|
// peers is a heap of peerDistance items
|
||||||
peers []*peerDistance
|
peers []*peerDistance
|
||||||
|
|
||||||
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pq distancePQ) Len() int {
|
func (pq *distancePQ) Len() int {
|
||||||
return len(pq.peers)
|
return len(pq.peers)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pq distancePQ) Less(i, j int) bool {
|
func (pq *distancePQ) Less(i, j int) bool {
|
||||||
return -1 == pq.peers[i].distance.Cmp(pq.peers[j].distance)
|
return -1 == pq.peers[i].distance.Cmp(pq.peers[j].distance)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pq distancePQ) Swap(i, j int) {
|
func (pq *distancePQ) Swap(i, j int) {
|
||||||
p := pq.peers
|
p := pq.peers
|
||||||
p[i], p[j] = p[j], p[i]
|
p[i], p[j] = p[j], p[i]
|
||||||
}
|
}
|
||||||
@ -54,6 +57,9 @@ func (pq *distancePQ) Pop() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pq *distancePQ) Enqueue(p *peer.Peer) {
|
func (pq *distancePQ) Enqueue(p *peer.Peer) {
|
||||||
|
pq.Lock()
|
||||||
|
defer pq.Unlock()
|
||||||
|
|
||||||
distance := ks.XORKeySpace.Key(p.ID).Distance(pq.from)
|
distance := ks.XORKeySpace.Key(p.ID).Distance(pq.from)
|
||||||
|
|
||||||
heap.Push(pq, &peerDistance{
|
heap.Push(pq, &peerDistance{
|
||||||
@ -63,6 +69,9 @@ func (pq *distancePQ) Enqueue(p *peer.Peer) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pq *distancePQ) Dequeue() *peer.Peer {
|
func (pq *distancePQ) Dequeue() *peer.Peer {
|
||||||
|
pq.Lock()
|
||||||
|
defer pq.Unlock()
|
||||||
|
|
||||||
if len(pq.peers) < 1 {
|
if len(pq.peers) < 1 {
|
||||||
panic("called Dequeue on an empty PeerQueue")
|
panic("called Dequeue on an empty PeerQueue")
|
||||||
// will panic internally anyway, but we can help debug here
|
// will panic internally anyway, but we can help debug here
|
||||||
|
Reference in New Issue
Block a user