Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this Singleton Implementation Thread-Safe?

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);
}
like image 841
SluggishNewb Avatar asked Dec 07 '25 08:12

SluggishNewb


1 Answers

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.

like image 58
Mestkon Avatar answered Dec 08 '25 21:12

Mestkon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!