c - C99中局部静态数组的线程安全

标签 c arrays thread-safety c99 static-variables

以下是线程安全的,因为每个数组元素仅由一个线程访问(包括此处未显示的真实世界部分):

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

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

现在考虑以下代码:

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

这个函数也是线程安全的吗(特别是考虑到在第一次调用函数时发生的数组初始化,而不是在启动时)?

最佳答案

很安全。所有具有静态存储持续时间的对象都在程序启动之前初始化。这意味着甚至在任何线程发挥作用之前。

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.

(强调我的)。

C99 没有线程的概念。但这就是我从标准中解释上述引述的方式。

关于c - C99中局部静态数组的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855483/

相关文章:

c++ - 从一对数组中获取匹配的元素 (C++/OpenCV)

arrays - MongoDB:如何获取查找集合的对象值

java - java.net.Socket 线程安全的方式是什么?

c - 如何声明函数一次传递一个参数 argv[i]?在C中

c - 通过简单地使用指向它中间的指针来拆分 C 数组是否是一种不好的做法?

c - TSORT 数组功能

java - 将 CSV 文件转换为 2D 数组 Java

C - 将未初始化的变量传递给函数

c# - 记录到文件或事件查看器?

c++ - 生产者/消费者设计 - 在 Qt 中跨线程共享队列变量