What Is Double Checked Locking?

Double check locking is a technique to make singleton design thread safe. Look at below pseudo code, there are two checks. The first thread that will acquire the lock will construct the  Singleton object and pInstance is initialized. If other threads call instance method then due to first check initialization step is ignored. Due to second check race condition is prevented if multiple threads will try to initialize Singleton simultaneously.

Double checked locking and singleton design patternLet us implement this with actual c++ code on Linux . Then again we will discuss its reliability.

Note: The above code looks to be thread safe however the solution is not correct on all architecture. The compiler optimization for instruction reordering can cause side effects. The above code can be modified using memory barrier technique for more reliable.

Memory barrier

Memory barrier is an instruction for processor that guaranty order of instructions. All instructions before the barrier  must be completed and before the instruction after the barrier.

Thread safe and c++ 11

According to c++ standard in section 6.7, static variables is always thread-safe. The following code ( from http://rosettacode.org/wiki/Singleton#Thread_safe_.28since_C.2B.2B11.29 ) is thread safe singleton design pattern.



Related Contents to follow