4

It is known that static initialization order fiasco (SIOF) can be solved by using construct on first use idiom (COFU). However, this solution may introduce the issue with race conditions when the variable is being initialized from multiple threads.

I tried to avoid both SIOF and race conditions in my project in a following way. I used COFU. And I forced initialization of target variable by using non-local variable (c_unusedNonLocal) in cpp. Thus, thanks to c_unusedNonLocal, even if there are no non-locals which access target variable via B::getA it is initialized anyway. What is important, it is initialized before main in a single thread. So, with read-only access there should be no race conditions and no SIOF.

Is this a feasible solution? Are there any possible pitfalls or I mistaken about initialization in a single thread or whatever?

Thanks.

a.h

struct A
{
    A() {}
};

b.h

struct B
{
    static const A& getA();
};

b.cpp

// force initialization before 'main'
// assuming that this happens in a single thread (thus no race conditions)
static const A& c_unusedNonLocal = B::getA();

const A& B::getA()
{
    static const A* result = new A();
    return *result;
}

main.cpp

int main() {
    // _read only_ access via B::getA is now thread safe
    // because object is guaranteed (?) to be initialized before main
    return 0;
}
tim
  • 788
  • 4
  • 14
  • "this solution may introduce the issue with race conditions when the variable is being initialized from multiple threads." No longer the case in C++11. – T.C. Aug 04 '14 at 15:47
  • See more at http://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11 – user3159253 Aug 04 '14 at 16:14
  • (+1) because: maybe seemm irrelevant for some, but the added "multithreading" tag reinforces the scenario, that also applies to non "multithreading" cases. – umlcat Aug 04 '14 at 17:31

0 Answers0