Thread safe singleton with deterministic destruction

153 views Asked by At

I want to create a thread safe singleton class.

The current way to achieve the same(that I know of) is by having a static method in the class which returns the static object as below:

Singleton & Singleton::getInstance()
{
    static Singleton instance;
    return instance;
}

The problem with having this approach is that since the created object is static, its cleanup happens at application exit. Ideally I would like to have control over when the destruction exactly happens.

I did some digging and found that I can use the static ptr to instance way and have a separate cleanup function, but to make it thread safe I will have to use double check locking with explicit memory barriers.

Is there a simpler to comprehend(I am not an expert) way to achieve the same?

0

There are 0 answers