Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static struct initialization thread safety

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++?

like image 737
fjanisze Avatar asked Aug 09 '26 09:08

fjanisze


1 Answers

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.

like image 145
Amit Avatar answered Aug 12 '26 01:08

Amit