Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c++ - Is static init thread-safe with VC2010?

I've been looking all around SO and MSDN for an answer to this question, but cannot seem to find a clear and final answer...

I know that it's in the C++11 standard and that current GCC version behave this way, but does VC2010 currently guarantees thread-safety of a local static variable initialization?

i.e.: Is this thread-safe with VC2010?

    static S& getInstance()
    {
        static S instance;
        return instance;
    }

...And if not, what is the current best practice to get a thread-safe singleton implementation in C++ with VC2010?

EDIT: As pointed out by Chris Betti's answer, VC2010 doesn't implement thread-safeness of local static variable init.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From Visual Studio 2010's documentation on Static:

Assigning a value to a static local variable in a multithreaded application is not thread safe and we do not recommend it as a programming practice.

The second part of your question has some good existing answers.

Updated Nov 22, 2015:

Others have verified, specifically, that static initialization is not thread safe either (see comment and other answer).

User squelart on VS2015:

you may want to add that VS2015 finally gets it right: https://msdn.microsoft.com/en-au/library/hh567368.aspx#concurrencytable ("Magic statics")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...