简体   繁体   English

C99中本地静态数组的线程安全

[英]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 : 5.1.2执行环境

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. 在这两种情况下,当执行环境调用指定的C函数时,都会发生程序启动。 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. C99没有线程的概念。 But that's how I'd interpret the above quote from the standard. 但这就是我从标准中解释以上引用的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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