I've read the question and answers here, and learned that a true thread-safe singleton can be implemented with correctly placed memory barrier, which is stated here in chapter 6. I've come up with my own version of singleton implementation, by reviewing the code I've seen no memory ordering problem so far, but it differs a lot from a typical DCLP approach. Do you think this is a reliable implementation?
static std::atomic<T*> _instance;
...
Singleton* get_instance() {
ins = _instance.load(std::memory_order_acquire);
if (ins == nullptr) {
T* temp = nullptr;
{
std::lock_guard<std::mutex> guard(_lock);
temp = new(std::nothrow) T;
}
if(!_instance.compare_exchange_strong(nullptr, temp, std::memory_order_release)) {
delete temp;
}
}
return _instance.load(std::memory_order_acquire);
}
It is hard to beat a simple
class Singleton { ... };
Singleton* get_instance()
{
static Singleton instance; // guaranteed to be thread safe in C++11
return &instance;
}
Any access to the pointer after it has been returned is still not thread safe, but neither is access in your implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With