From 7573f6a556bab250b93c479e4b4e1fbf09859729 Mon Sep 17 00:00:00 2001 From: AntiochP <30642645+antiochp@users.noreply.github.com> Date: Tue, 21 Nov 2017 22:28:31 -0500 Subject: [PATCH] use read lock over write lock where possible (#363) fix issue with sync starting twice --- grin/src/adapters.rs | 4 ++-- p2p/src/server.rs | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/grin/src/adapters.rs b/grin/src/adapters.rs index ffbc81f5e..3be2cdd42 100644 --- a/grin/src/adapters.rs +++ b/grin/src/adapters.rs @@ -259,7 +259,7 @@ impl NetAdapter for NetToChainAdapter { ); if diff.into_num() > 0 { - let peers = self.connected_peers.write().unwrap(); + let peers = self.connected_peers.read().unwrap(); if let Some(peer) = peers.get(&addr) { let mut peer = peer.write().unwrap(); peer.info.total_difficulty = diff; @@ -293,7 +293,7 @@ impl NetToChainAdapter { .name("syncer".to_string()) .spawn(move || { let res = arc_sync.run(); - if let Err(e) = arc_sync.run() { + if let Err(e) = res { panic!("Error during sync, aborting: {:?}", e); } }); diff --git a/p2p/src/server.rs b/p2p/src/server.rs index 6a63a58c4..d4e030e38 100644 --- a/p2p/src/server.rs +++ b/p2p/src/server.rs @@ -278,6 +278,10 @@ impl Server { let p = p.read().unwrap(); p.info.total_difficulty.clone() }); + + // TODO we should shuffle here + // we want a random peer with highest total_difficulty + let peer = peers.last().unwrap(); Some(peer.clone()) } @@ -329,16 +333,16 @@ impl Server { /// Number of peers we're currently connected to. pub fn peer_count(&self) -> u32 { - self.peers.read().unwrap().len() as u32 + self.all_peers().len() as u32 } /// Stops the server. Disconnect from all peers at the same time. pub fn stop(self) { info!(LOGGER, "calling stop on server"); let peers = self.all_peers(); - for p in peers { - let p = p.write().unwrap(); - p.stop(); + for peer in peers { + let peer = peer.read().unwrap(); + peer.stop(); } self.stop.into_inner().unwrap().send(()).unwrap(); } @@ -357,8 +361,10 @@ where adapter.peer_connected(&peer.info); let addr = peer.info.addr.clone(); let apeer = Arc::new(RwLock::new(peer)); - let mut peers = peers.write().unwrap(); - peers.insert(addr, apeer.clone()); + { + let mut peers = peers.write().unwrap(); + peers.insert(addr, apeer.clone()); + } Ok((conn, apeer)) }); Box::new(peer_add)