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

Categories

According to following resources, in C++(Specially Visual C++) scoped static variable initialization isn't thread safe. But, global static variables are safe.

Thread-safe static variables without mutexing?

http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx

So, is following code with static member variable thread-safe?

class TestClass
{
public:
   static MyClass m_instance;
}

Myclass TestClass::m_instance;

Thanks in advance!

See Question&Answers more detail:os

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

1 Answer

It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.

All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing function is called. The standard is silent on the question of how function-level statics are constructed when the function is called on multiple threads. However, every implementation I've worked with uses a lock around the constructor (with a twice-checked flag) to guarantee thread-safety.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...