Double check is often seen in concurrent programming, many people will use, but only double check is still not enough, will produce the problem of reorder; take the double check in the singleton pattern get_instance interface for example, as follows:
This error may occur when m_instance_ptr = new singleton(), a statement that is not an atomic operation, which we can simply understand as (allocate memory, constructor call, assign to m_instance_ptr) three steps. And these three parts may change the order in the compiler or when optimizing in the execution unit, which is not a problem for the code in the critical area, but when the order changes to (allocate memory, assign to m_instance_ptr,constructor call), plus the first level of check is a problem; when the execution gets to assign to m_instance_prt, which is not yet no constructor call, another concurrent execution to the first check, directly returned the object without the execution of the constructor, will appear as the defined behavior. And in most languages there will be this reorder problem. To cope with this kind of problem, java introduced the volidate keyword; but c++ does not have a keyword that can achieve the same effect; and after c++11 we can have several ways to solve this problem; * use std::call_once
Static local variables According to the standard, §6.7 [stmt.dcl] p4 Visual Studio: supported since Visual Studio 2015 GCC: supported since GCC 4.3
Atomic variables + memory order