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.
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.