What is possibly happening in this C++ Singleton used in a multi-threaded code and how to possibly fix the behavior?

51 Views Asked by At

There is this simple Singleton function:

const AppConfig& AppConfig::Singleton()
{
    static AppConfig appConfig{ configPath_ };

    return appConfig;
}

first, it's initialized correctly every time (I have breakpoints for checking it) and it is called multiple times from multiple threads with following ways:

auto& a = utils::AppConfig::Singleton();

or

utils::AppConfig::Singleton().member

Basically, it uses the implementation from this answer: https://stackoverflow.com/a/1008289/1423254, which I personally used many times as well thinking that it is thread-safe and it should be according to :https://stackoverflow.com/a/1661564/1423254.

The code works on production, but not locally on my laptop, quite often with some garbage in the returned config:

incorrect data

What is happening there and how to fix it so I don't get that garbage data?

I even tried putting a lock inside the whole Singleton function body and it didn't help.

We use 64bit GCC 7.5.0 for compilation.

EDIT: I should add that multiple threads call the Singleton function correctly, there is a problem just with 1 individual thread, sometimes returning garbage.

0

There are 0 best solutions below