Commit 3c0c02e2 authored by acud's avatar acud Committed by GitHub

kademlia: change pslice mutex to use rwmutex (#313)

parent 26d2f835
......@@ -91,19 +91,24 @@ func New(o Options) *Kad {
// manage is a forever loop that manages the connection to new peers
// once they get added or once others leave.
func (k *Kad) manage() {
var peerToRemove swarm.Address
var (
peerToRemove swarm.Address
start time.Time
)
defer close(k.done)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-k.quit
cancel()
}()
for {
select {
case <-k.quit:
return
case <-k.manageC:
start = time.Now()
err := k.knownPeers.EachBinRev(func(peer swarm.Address, po uint8) (bool, bool, error) {
if k.connectedPeers.Exists(peer) {
return false, false, nil
......@@ -166,6 +171,7 @@ func (k *Kad) manage() {
// be made before checking the next peer, so we iterate to next
return false, false, nil
})
k.logger.Tracef("kademlia iterator took %s to finish", time.Since(start))
if err != nil {
if errors.Is(err, errMissingAddressBookEntry) {
......
......@@ -19,7 +19,7 @@ type PSlice struct {
peers []swarm.Address // the slice of peers
bins []uint // the indexes of every proximity order in the peers slice, index is po, value is index of peers slice
sync.Mutex
sync.RWMutex
}
// New creates a new PSlice.
......@@ -32,8 +32,8 @@ func New(maxBins int) *PSlice {
// iterates over all peers from deepest bin to shallowest.
func (s *PSlice) EachBin(pf topology.EachPeerFunc) error {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
if len(s.peers) == 0 {
return nil
......@@ -63,8 +63,8 @@ func (s *PSlice) EachBin(pf topology.EachPeerFunc) error {
// EachBinRev iterates over all peers from shallowest bin to deepest.
func (s *PSlice) EachBinRev(pf topology.EachPeerFunc) error {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
if len(s.peers) == 0 {
return nil
......@@ -96,8 +96,8 @@ func (s *PSlice) EachBinRev(pf topology.EachPeerFunc) error {
}
func (s *PSlice) Length() int {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
return len(s.peers)
}
......@@ -105,8 +105,8 @@ func (s *PSlice) Length() int {
// ShallowestEmpty returns the shallowest empty bin if one exists.
// If such bin does not exists, returns true as bool value.
func (s *PSlice) ShallowestEmpty() (bin uint8, none bool) {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
binCp := make([]uint, len(s.bins)+1)
copy(binCp, s.bins)
......@@ -122,8 +122,8 @@ func (s *PSlice) ShallowestEmpty() (bin uint8, none bool) {
// Exists checks if a peer exists.
func (s *PSlice) Exists(addr swarm.Address) bool {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
b, _ := s.exists(addr)
return b
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment