Could double-checked locking accidentally happen to work?

anthony_williams
Total Points:
1,565
Status Points:
1,065
Brown Belt
July 7, 2009 9:00 AM PDT
Rate
 
#1
Quoting - Raf Schietekat
With the implementation used in "C++ and the Perils of Double-Checked Locking" (Example 3), could it be that with g++ optimisation turned off on x64 running 32-bit or 64-bit Linux it turns out that the first read is in fact always a load-acquire and the final assignment a release-store? I would use atomic operations myself, but what do you say to somebody who thinks that it's a bigger hassle to adopt, e.g., Threading Building Blocks for its atomics support, than to trust that the problem will not manifest itself? Maybe it does turn out that everything is aligned (even 64-bit pointers on 64-bit Linux), that the compiler always uses single load/store instructions, that loads are always ordered even if this is not officially documented, and that I'm making a fuss over nothing at all?

The nature of undefined behaviour is that anything may happen --- including the possibility that everything may behave as you naively expect. It is therefore entirely possible that this code may turn out to be safe on some particular compiler/compiler setting/platform combination.

However, I would strongly recommend against relying on this, as the smallest change could affect the behaviour so that it is no longer what you may expect.

In particular, the compiler may choose to generate the write to pInstance before it invokes the constructor of the new Singleton object --- it has to make that store anyway, and it provides somewhere to write the value whilst it calls the constructor.

If the compiler does do so, then it doesn't matter whether the instruction is a release store or not --- another thread might see the non-NULL value before the constructor has completed, thus hitting a race condition.

If you are going to rely on compiler and platform specific behaviour, then you are better off using the compiler-specific atomic primitives such as the gcc __sync_xxx builtins. Such primitives will have a documented consequence on the compiler behaviour, and might therefore provide the requisite guarantees.


Intel Software Network Forums Statistics

8479 users have contributed to 31611 threads and 100667 posts to date.
In the past 24 hours, we have 31 new thread(s) 108 new posts(s), and 167 new user(s).

In the past 3 days, the most popular thread for everyone has been gemm(A,A,A) like possible? The most posts were made to gemm(A,A,A) like possible? The post with the most views is Dear Steve, excuse me for a d

Please welcome our newest member zhpn