MiP
MiP

Reputation: 6422

Singleton pattern with atomic states

Is it a correct way to make singleton objects by using 2 static atomic and mutex variables to save 2 states: initializing and initialized?

For example, I only need one Application instance running in a program. Its job is to init and terminate external libraries, and prevent to create any new Application object.

#include <mutex>
#include <stdexcept>
static bool initialized;
static std::mutex mutex;
Application::Application()
{
    std::lock_guard<std::mutex> lock(mutex);

    if (initialized) throw std::runtime_error("Application::Application");

    if (!init_external_libraries())
        throw std::runtime_error("Application::Application");

    initialized = true;
}
Application::~Application()
{
    terminiate_external_libraries();
    initialized = false;
}

Upvotes: 1

Views: 461

Answers (1)

Peter Pannel
Peter Pannel

Reputation: 39

Do I get it right, that init_external_libraries() has to run at most one time?

Atomics won't help you there. Operations on atomics are atomic (storing and loading values in your case), but what happens between those is not.

You could use that nice trick of having a function that has a static object and returns a reference to it. As far as I know, initialization of static values are guaranteed to happen only once.

It would look something like this:

Object &get_singleton(){
    static Object o;
    return o;
}

EDIT: And, as far as I know, this is threadsafe. Don't quote me on that though.

Upvotes: 1

Related Questions