在GCC中函数静态变量是线程安全的吗?

问题描述:

在示例代码

void foo()
{
  static Bar b;
  ...
}

>是否保证将以线程安全的方式创建和初始化 b

compiled with GCC is it guaranteed that b will be created and initialized in a thread-safe manner ?

在gcc的手册页,发现 -fno-threadsafe-statics 命令行选项:

In gcc's man page, found the -fno-threadsafe-statics command line option:


不要放出额外的代码
例程在C ++ ABI中为
指定的本地
静态的线程安全初始化。您可以使用此选项
稍微减少代码大小,
不需要是线程安全的。

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. 这是否意味着,默认情况下本地静态是线程安全的GCC?所以没有理由要明确保护。与 pthread_mutex_lock / unlock

如何编写可移植代码 - 如何检查编译器是否会添加卫兵?还是最好关闭GCC的此功能?

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 ?



  1. 不,它意味着本地 static 初始化是线程安全的。

您确定要启用此功能。线程安全的初始化局部 static 是非常重要的。如果你需要通常线程安全访问本地 static ,那么你需要自己添加适当的保护。

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.