use read lock over write lock where possible (#363)

fix issue with sync starting twice
This commit is contained in:
AntiochP 2017-11-21 22:28:31 -05:00 committed by GitHub
parent c325c99b87
commit 7573f6a556
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 8 deletions

View file

@ -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);
}
});

View file

@ -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());
}
Ok((conn, apeer))
});
Box::new(peer_add)