《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.8
也就是说线程B执行到正在线程A中初始化的静态变量时,要等待完成。这规定了构造函数的锁定等待特性。
在3.6.3 Termination [basic.start.term] 第1节,描述了程序结束时,静态/动态变量析构的顺序。
Destructors for initialized objects with thread storage duration within a given thread are called as a result of returning from the initial function of that thread and as a result of that thread calling std::exit.
The completions of the destructors for all initialized objects with thread storage duration within that thread are sequenced before the initiation of the destructors of any object with static storage duration. If the completion of the constructor or dynamic initialization of an object with thread storage duration is sequenced before that of another, the completion of the destructor of the second is sequenced before the initiation of the destructor of the first.
动态定义的局部变量在程序执行出其作用域时发生析构,线程local生命周期(thread storage duration)的对象在线程初始化函数返回后发生析构,或调用线程exit是析构。线程生命周期的对象全部在静态变量之前析构,静态变量按照后构造的先析构的栈式顺序释放。
此特性称为“Dynamic Initialization and Destruction with Concurrency”。
▐ 编译器实现
从c++ 11特性表中看到 gcc 4.3、 clang 2.9、MSVC 19.0 开始实现此特性。Apple clang不知道什么版本,只有一个Yes.
查阅GCC资料详情, 已经支持了静态变量构造和析构函数的多线程安全,特性为“Dynamic Initialization and Destruction with Concurrency”。
构造阶段:对于局部静态变量,多线程调用时,首先构造静态变量的线程先加锁,其他线程并不是按照已经初始化了继续执行,而是等待前者执行完的锁。对于全局静态变量,按照声明顺序在主线程构造,早于子线程启动。
析构阶段:全局和局部静态变量的析构函数在所有线程结束后才开始调用,保证析构时线程安全。
GCC从 GCC 4.3开始支持 , Visual Studio从Visual Studio 2015开始支持。 需要明确的是,这里的线程安全只是构造函数、析构函数阶段,如果在这两个阶段之间,在多个线程访问静态变量的含有有写操作的成员函数,或某种异步操作的函数,仍然是不安全的。如果调用只读内部数据的函数,则不会产生竞争。
对应的编译选项为负向开关:fno-threadsafe-statics, 在c++11和以后版本默认是打开这个特性的,仍然可以关闭。
-fno-threadsafe-statics
Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn’t need to be thread-safe.
本机apple 的clang编译器版本为12.0.5,由于Apple未明确支持多线程析构构造版本,只写了一个Yes, 所以还不清楚什么版本支持。后续会看到实际看到的效果,属于部分支持。
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: x86_64-apple-darwin20.3.0
Thread model: posix