GCC中的函数静态变量是线程安全的吗? [英] Are function static variables thread-safe in GCC?

查看:23
本文介绍了GCC中的函数静态变量是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例代码中

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

GCC 编译是否保证 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.

这篇关于GCC中的函数静态变量是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆