c++ - 关于多线程环境下static const变量的使用

标签 c++ thread-safety

我正在尝试了解潜在的场景以及它是否可能成为问题。

所以我有一个当前线程安全的静态函数。 函数是这样的:

static thread_safe_func()
{
    ... process
}

现在在此函数中,我添加以下内容:

static thread_safe_func()
{
  static const Class::NonThreadSafeClassName() *array[16] = {
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
  }
  ... code continues here
}

现在它本身是线程安全的吗? 该数组将在应用程序的整个生命周期内初始化一次,因此一旦函数 thread_safe_func() 被调用并完全运行,我希望它是线程安全的。

问题显然是第一次通话时可能发生的情况, 在一个线程调用 thread_safe_func() 的情况下会发生什么,const 数组的初始化发生,但在初始化完成之前,另一个线程正在调用 thread_safe_func()。

将更改为:

static ClassMutex lock = ClassMutex()

static thread_safe_func()
{
  lock.Lock()
  static const Class::NonThreadSafeClassName() *array[16] = {
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
    Class::NonThreadSafeClassName(),
  }
  lock.Unlock()
  ... code continues here
}

值得并保证此代码现在是线程安全的吗?

最佳答案

C++03 下,两者都...

void foo() {
  static your_variable = ...;
}

...也不...

void foo() {
    lock.Lock();
    static your_variable = ...;
    lock.Unlock();
}

...是线程安全的。

第一个不是线程安全的,因为标准没有说明第二个线程在第一个线程仍在执行初始化时进入函数。事实上,标准根本没有线程的概念。

第二个不是线程安全的,因为初始化发生在执行流进入函数时(第一次),这是之前 lock.Lock().


C++11 中,initialization of the local static variable is thread safe .

关于c++ - 关于多线程环境下static const变量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9559400/

相关文章:

java - SplittableRandom.split() 线程安全吗?

c - 为什么 __thread 必须跟在 extern 或 static 之后

python - 为什么 `celery.current_app` 引用 Flask View 函数中的默认实例

java - 是否需要从应用程序的 main 方法切换到 Swing 线程?

c++ - 为模板化容器类专门化成员函数

c++ - Windows DLL 中的字符串表在哪里?

c++ - R6010-当 boost 文件系统的重命名或 copy_file 方法被命中时,中止被命中

C++:我可以将非静态成员变量的值赋给静态成员变量吗?

c# - 包装托管代码以供非托管使用

multithreading - 编译时-pthread和-lpthread之间的区别