简体   繁体   中英

Thread safety of local static array in C99

The following is thread safe since each array element is accessed by only one thread (including the real world part not shown here):

static bool myArray[THREAD_COUNT] = {false}; // Only used in DoSomething()

void DoSomething(uint8_t threadIndex)
{
   myArray[threadIndex] = true;
   // Real world function is more complex
}

Now consider the following code:

void DoSomething(uint8_t threadIndex)
{
   static bool myArray[THREAD_COUNT] = {false};
   myArray[threadIndex] = true;
   // Real world function is more complex
}

Is this function threadsafe too (especially considering the array initialization that takes place at first call of the function, not at startup)?

It's safe. All objects with static storage duration are initialized before program startup. That means even before any threads come into play.

5.1.2 Execution environments :

Two execution environments are defined: freestanding and hosted. In both cases, program startup occurs when a designated C function is called by the execution environment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.

(emphasis mine).

C99 didn't have the concept of threads. But that's how I'd interpret the above quote from the standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM