Reference:- “Modern C++ Design: Generic Programming and Design Patterns Applied” by Andrei Alexandrescu
Chapter 6 Implementing Singletons.
Even if you put volatile then also it is not guaranteed to make Double Check locking pattern safe and portable.Why it is so?
If some one can put any good link that explains what is relaxed memory model and what is exactly problem with Double Check pattern.{Or someone can explain}
I used to think volatile has solve the problem but seems its not correct until I read the book.
I’ll try to provide some context.
There are three (Boehm & McLaren) portable use cases for
volatilein C++ none of which has anything to do with multithreading. Alexandrescu did come up with a hack a long time back to cajole C++’s type system to help with multithreaded programming but that’s that. See David Butenhof’s reply on comp.programming.threads regarding the same.The confusion regarding this qualifier stems from the fact that with some compilers (Intel’s for example)
volatilebrings into play memory fence semantics — which is what you need for safe multithreading. But this is not portable and should not be relied upon.Further, most professional grade compilers fail to implement
volatileflawlessly. See Regehr et al.Confusion probably gathers much from the fact that Java, the other language, has completely different semantics for
volatileand they do involve memory fences. However, note that even the Double Checked Locking is not free from issues.