Multithreading – dual locking mode in C 11?
The new model of C 11 allows multiprocessor systems to work reliably, wrt Reorganization order
As Meyers and Alexandrescu pointed out, the implementation of "simple" double locking mode in C 03 is unsafe
Singleton* Singleton::instance() { if (pInstance == 0) { // 1st test Lock lock; if (pInstance == 0) { // 2nd test pInstance = new Singleton; } } return pInstance; }
They said in their article that no matter what you do, as a programmer, there are too many freedoms in the C 03 compiler: allow reordering instructions, and you can't be sure that you end up with only one singleton instance
My question now is:
>The limitations / definitions of the new C11 machine model now constrain the instruction sequence, and the above code will always be used with the C 11 Compiler? > How to use the new library facilities (instead of the analog lock here), and how secure is this singleton mode?
Solution
If pinstance is a regular pointer, the code has a potential data race - the operation on the pointer (or any built-in type) cannot be guaranteed to be atomic (editing or ordered)
If pinstance is an STD:: atomic < singleton * > and lock internally uses STD:: mutex to achieve synchronization (for example, if lock is actually STD:: lock_guard < STD:: mutex >), the code should be unlimited
Please note that you need explicit locking and atomic pinstance to achieve correct synchronization