Skip to content

Commit f0fdda0

Browse files
committed
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.
1 parent 3b9a0bf commit f0fdda0

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/main.cpp

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
#include "validationinterface.h"
3838
#include "versionbits.h"
3939

40+
#include <atomic>
4041
#include <sstream>
4142

4243
#include <boost/algorithm/string/replace.hpp>
@@ -1574,18 +1575,24 @@ CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
15741575
bool IsInitialBlockDownload()
15751576
{
15761577
const CChainParams& chainParams = Params();
1578+
1579+
// Once this function has returned false, it must remain false.
1580+
static std::atomic<bool> latchToFalse{false};
1581+
// Optimization: pre-test latch before taking the lock.
1582+
if (latchToFalse.load(std::memory_order_relaxed))
1583+
return false;
1584+
15771585
LOCK(cs_main);
1586+
if (latchToFalse.load(std::memory_order_relaxed))
1587+
return false;
15781588
if (fImporting || fReindex)
15791589
return true;
15801590
if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
15811591
return true;
1582-
static bool lockIBDState = false;
1583-
if (lockIBDState)
1584-
return false;
15851592
bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
15861593
std::max(chainActive.Tip()->GetBlockTime(), pindexBestHeader->GetBlockTime()) < GetTime() - nMaxTipAge);
15871594
if (!state)
1588-
lockIBDState = true;
1595+
latchToFalse.store(true, std::memory_order_relaxed);
15891596
return state;
15901597
}
15911598

0 commit comments

Comments
 (0)