在示例代码中
void foo()
{
static Bar b;
...
}
用 GCC 编译是否保证 b
将以线程安全的方式创建和初始化?
在 gcc 的手册页中,找到 -fno-threadsafe-statics 命令行选项:
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.
这是否意味着本地静态变量在默认情况下使用 GCC 是线程安全的?所以没有理由进行明确的保护,例如使用
pthread_mutex_lock/unlock
?如何编写可移植代码 - 如何检查编译器是否会添加其保护?还是关闭GCC的这个功能更好?
最佳答案
不,这意味着本地
static
的初始化是线程安全的。您肯定希望启用此功能。本地
static
的线程安全初始化非常重要。如果您通常需要对本地static
进行线程安全访问,那么您需要自己添加适当的保护。
关于c++ - GCC中的函数静态变量是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1270927/