静态结构初始化线程安全

huangapple go评论69阅读模式
英文:

static struct initialization thread safety

问题

给定以下示例:

struct test
{
    const char* data;
    const int number;
};

struct test* foo()
{
    static struct test t = {
        "this is some data",
        69
    };
    return &t;
}

调用 foo 是线程安全的吗?换句话说,结构体是否以线程安全的方式仅初始化一次?如果这是在C或C++中编译,是否会有区别?

翻译完成,不包含代码。

英文:

Given the following example:

struct test
{
    const char* data;
    const int number;
};

struct test* foo()
{
    static struct test t = {
        "this is some data",
        69
    };
    return &t;
}

is the call to foo thread safe? In other words, is the structure initialized only once in a thread-safe manner? Does it make a difference if this is compiled in C or C++?

答案1

得分: 4

C/C++ 在 C++ 11 之前和 C++ 11 以及之后存在区别(早期标准没有任何线程相关的规定)。

正如你在这里所看到的:C++ 静态局部变量自从 C++11,标准保证静态局部变量只会初始化一次。有一个特定的注释可以用于确保在多线程环境中进行单一初始化的锁定:

如果多个线程同时尝试初始化相同的静态局部变量,初始化将仅发生一次(对于任意函数,可以使用 std::call_once 来获得类似的行为)。
注意:这一特性的通常实现使用了双重检查锁定模式的变种,它减少了已初始化的本地静态变量的运行时开销,将其减少为单个非原子布尔比较。

C 中的规则在这里指定:C 存储期

静态存储期。存储期为整个程序的执行过程,对象中存储的值只会在 main 函数之前初始化一次。所有声明为静态的对象以及所有具有内部或外部链接的对象(自 C11 起未声明为 _Thread_local)都具有这种存储期。

英文:

The distinction exists in C/C++ prior to C++ 11 and in C++ 11 or later (Earlier standards lacked any provisions for threading.).

As you can see here: C++ Static local variables, since C++11 is it guaranteed by the standard that a static local variable will be initialized only once. There is a specific note regarding locks that can be applied to ensure single initializing in a multi threaded environment:

> If multiple threads attempt to initialize the same static local
> variable concurrently, the initialization occurs exactly once
(similar
> behavior can be obtained for arbitrary functions with std::call_once).
> Note: usual implementations of this feature use variants of the
> double-checked locking pattern, which reduces runtime overhead for
> already-initialized local statics to a single non-atomic boolean
> comparison.

The rules in C are specified here: C Storage duration:

> static storage duration. The storage duration is the entire execution
> of the program, and the value stored in the object is initialized only
> once, prior to main function
. All objects declared static and all
> objects with either internal or external linkage that aren't declared
> _Thread_local (since C11) have this storage duration.

答案2

得分: 0

自C++11开始,对象初始化将仅由一个线程进行,其他线程将等待直到初始化完成。参考此线程

英文:

Since C++11, object initialization will be made only by one thread, other threads will wait till it complete. See this thread for reference.

huangapple
  • 本文由 发表于 2023年2月6日 15:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定