How to utilize double check locking in C# correctly
The major benefit of double check locking is to reduce the overhead of acquiring a lock by first testing the locking in an unsafe manner under a multi-threaded environment. It is widely used in the scenarios such as lazy initialization. Typical pseudo code would be like followings:
IF (VAR_X meets certain conditions) { ACQUIRE_LOCK(); IF (VAR_X meets certain conditions) { VAR_X = NEW_VAR_X; DO_SOMETHING_ELSE(); } RELEASE_LOCK(); } USE(VAR_X); |
Unfortunately, due to the aggressive optimization of modern compiler, thread A might possibly access partial result of VAR_X before thread B actually completes updating it. As a result, the app will probably crash.
In C#, to ensure the correctness, we should declare VAR_X as volatile to ensure the assignment to the VAR_X completes before it can be accessed. I am working on a sample to demonstrate this; Can anyone share working code before I post my version out?
Singleton implementation in msdn: https://msdn.microsoft.com/en-us/library/ms998558.aspx