From 1ed6d18a3c1ec8990f1df49815cc3aee7d86a852 Mon Sep 17 00:00:00 2001 From: Kaz Wesley Date: Tue, 26 Apr 2016 17:21:22 -0700 Subject: [PATCH] IsInitialBlockDownload: usually avoid locking Optimistically test the latch bool before taking the lock. For all IsInitialBlockDownload calls after the first to return false, this avoids the need to lock cs_main. --- src/main.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 39df28b91..33b2a0f35 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -43,6 +43,7 @@ #include "key.h" #include "wallet/wallet.h" +#include #include #include @@ -1784,20 +1785,26 @@ CAmount GetProofOfStakeSubsidy() bool IsInitialBlockDownload() { const CChainParams& chainParams = Params(); + + // Once this function has returned false, it must remain false. + static std::atomic latchToFalse{false}; + // Optimization: pre-test latch before taking the lock. + if (latchToFalse.load(std::memory_order_relaxed)) + return false; + LOCK(cs_main); + if (latchToFalse.load(std::memory_order_relaxed)) + return false; if (fImporting || fReindex) return true; if (chainActive.Tip() == NULL) return true; if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork)) return true; - static bool lockIBDState = false; - if (lockIBDState) - return false; bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 || pindexBestHeader->GetBlockTime() < GetTime() - nMaxTipAge); if (!state) - lockIBDState = true; + latchToFalse.store(true, std::memory_order_relaxed); return state; }