Why does the bitcoin mining code have the same if statement twice? 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 &gt; 4000)
{
    static CCriticalSection cs;
    {
        LOCK(cs);
        if (GetTimeMillis() - nHPSTimerStart &gt; 4000)
        {
        ....


Why is the same if statement "if (GetTimeMillis() - nHPSTimerStart &gt; 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!
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.