Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ static member variable initialization thread-safe?

Tags:

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!

like image 454
Varuna Avatar asked Dec 26 '09 08:12

Varuna


People also ask

Is initialization of static variable thread-safe?

So yes, you're safe.

Is static member thread-safe?

Thread SafetyStatic variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.

Is ++ thread-safe in C?

++ is not defined as thread-safe.


2 Answers

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.

like image 81
Marcelo Cantos Avatar answered Oct 15 '22 20:10

Marcelo Cantos


Yes(*). When global statics are initialized, there is only one thread around and all constructors are called on it. This is not true for function's statics, though.

(*) One can possibly make global statics not thread-safe by creating threads in some of the constructors and scheduling some initialization stages on these threads. In this case usual thread safety rules apply.

like image 25
Rom Avatar answered Oct 15 '22 19:10

Rom