Are function static variables thread-safe in GCC?

c++, gcc, initialization, static, thread-safety

Solution

No, it means that the initialization of local `static`s is thread-safe.

You definitely want to leave this feature enabled. Thread-safe initialization of local `static`s is very important. If you need generally thread-safe access to local `static`s then you will need to add the appropriate guards yourself.

Problem

In the example code ``` void foo() { static Bar b; ... } ``` compiled with GCC is it guaranteed that `b` will be created and initialized in a thread-safe manner ? In gcc's man page, found the -fno-threadsafe-statics command line option: Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe. Does it mean, that local statics are thread-safe by default with GCC ? So no reason to put explicit guarding e.g. with `pthread_mutex_lock/unlock` ? How to write portable code - how to check if compiler will add its guards ? Or is it better to turn off this feature of GCC ?

Original source