I have read many questions considering thread-safe double checked locking (for singletons or lazy init). In some threads, the answer is that the pattern is entirely broken, others suggest a solution.
So my question is: Is there a way to write a fully thread-safe double checked locking pattern in C++? If so, how does it look like.
We can assume C++11, if that makes things easier. As far as I know, C++11 improved the memory model which could yield the needed improvements.
I do know that it is possible in Java by making the double-check guarded variable volatile. Since C++11 borrowed large parts of the memory model from the one of Java, so I think it could be possible, but how?
std::call_once
. – Fidelecall_once
: How does this ensure that call once will not write the not fully created reference to the variable? – Whitishcall_once
ensures the subject is only ever called once; and that no other call tocall_once
returns before the one that actually executes the function returns (you can read more here en.cppreference.com/w/cpp/thread/call_once). How it does that is up to the implementation. These two things basically exist so you don't want to bother with writing more <strike>bugs</strike> double-checked locking implementations. – Fidele