Hacker News new | ask | show | jobs
by Manishearth 3991 days ago
On C++ if we're using a bool as the "check" and pthread_mutex_lock on a regular mutex would that work, or do we still need to hardcode fences?

(Asking because this pattern is used by libcxxabi code)

2 comments

A few years ago, the C++ standard didn't guarantee that the double-checked idiom would work. Even if your threading library had some way to insert the necessary memory barriers, it was possible that your compiler would optimize important things away.

C++11 changes that. The language now has standard ways to add memory barriers, and compiler optimizations can't remove them.

Yes, this is broken on certain architectures like PPC. Another core may see the "check" bool as set, but the fields of the protected object as uninitialized. One way to address this is to insert a write barrier just before setting the check bool, and a read barrier just after reading it.