2

From the v0.9.3 miner.cpp source (https://github.com/bitcoin/bitcoin/blob/v0.9.3/src/miner.cpp#L598-L604):

if (GetTimeMillis() - nHPSTimerStart > 4000)
{
    static CCriticalSection cs;
    {
        LOCK(cs);
        if (GetTimeMillis() - nHPSTimerStart > 4000)
        {
        ....

Why is the same if statement "if (GetTimeMillis() - nHPSTimerStart > 4000)" executed twice? GetTimeMillis() can only go up, so it seems like if the first one is true, then the second statement can only ever evaluate to true as well, and is useless. I'm assuming this is not entirely correct, though, and am also assuming it has something to do with the CCriticalSelection, but would like to understand the nature of it better.

Thanks!

5
  • I agree, I think that's a copy-paste bug. Maybe you should ask #bitcoin-dev to double-check.
    – Nick ODell
    Dec 4, 2014 at 22:01
  • 1
    Can any other thread modify nHPSTimerStart? Dec 5, 2014 at 0:31
  • Yes, I think so. There could be quite a few threads working on the mining.
    – morsecoder
    Dec 5, 2014 at 0:45
  • 1
    I have used something similar before. The first if checks if we should bother to do the potentially expensive lock. If yes, then we lock and now that nHPSTimerStart is guaranteed not to change we can safely execute the if again.
    – Floris
    Dec 5, 2014 at 13:13
  • Thanks, Floris, that seems reasonable. If you post as an answer, I could mark it as such.
    – morsecoder
    Dec 11, 2014 at 0:17

1 Answer 1

3

This is double-checked locking, which is

...a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion [...] without actually acquiring the lock.

This pattern can be fraught with issues; even folks who otherwise know what they're doing can be bitten by subtle issues. See, for example, C++ and the Perils of Double-Checked Locking by Scott Meyers and Andrei Alexandrescu.

The particular use case you cite looks fairly innocuous, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.