我正在尝试了解潜在的场景以及它是否可能成为问题。
所以我有一个当前线程安全的静态函数。 函数是这样的:
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/