Are function static variables thread-safe in GCC?

CsTamas picture CsTamas · Aug 13, 2009 · Viewed 26.8k times · Source

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.

  1. 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 ?

  2. 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 ?

Answer

CB Bailey picture CB Bailey · Aug 13, 2009
  1. No, it means that the initialization of local statics is thread-safe.

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