C++ Static变量跨平台、多线程安全性分析
灵钧2021-09-24

单例模式编程语言的多线程安全。

单例模式开始讨论

常见的编程语言,不论强类型弱类型,还是Just In Time(JIT)或Ahead of Time(AOT)的语言,都会涉及到设计模式,其中最经典的就是单例模式,有两种基本形式称为 Meyers Singleton , Gamma Singleton, 那么他们多线程安全吗?

// Meyers Singleton Pattern
class Singleton {
public:
static Singleton& getInstance() {
    static Singleton instance;
    return instance;
    }
private:
    Singleton();
}
// Gamma Singleton ; J. Nakamura
class Singleton {
public:
static Singleton* getInstance() {
      if (!m_pInstance) {
          m_pInstance = new Singleton();
          return m_pInstance;
      }
      return m_pInstance;
}
private:
    Singleton();
  static Singleton* m_pInstance;
}
// in cpp add:
Singleton* Singleton::m_pInstance = NULL;

我自己也经常使用到单例模式,包括在多线程场景原来还未遇到异常,在 MNN推理引擎中部分逻辑类似如下,与以上单例模式类似,使用的是全局静态变量。

class Machine
{
public:
    Machine(int year_) : year(year_) {}
    ~Machine() {
      year = -1; // released
    }
    int GetData() const {
        return year;
    }
    int year;
    // Parameters param;
};
static const Machine golbalMachine(100);

// called from multi-threads
bool checkMachine(int year)
{
    // read something from golbalMachine
    return golbalMachine.GetData() == year;
}

上周手淘日志平台开始出现一种崩溃案例,IOS平台 MNN推理引擎中出现了静态变量相关的crash,如下所示,子线程崩溃时,主线程在调用_exit函数。实际的代码中存在子线程访问静态变量的情况,类似checkMachine中异常crash,观察到出现概率很低。

Exception Type:  EXC_BAD_ACCESS
Exception Codes: KERN_INVALID_ADDRESS at 0x000095f59f17ce20
Exception Subtype: SIGSEGV
Triggered by Thread:  28

Thread 0:
0   Proximity                       0x00000001b115eb4c -[PRProximityEstimator initSingleThresholdEstmatorWithDelegate:delegateQueue:].cold.1 :668 (in Proximity)
1   libsystem_c.dylib               0x0000000197db7064 __cxa_finalize_ranges :416 (in libsystem_c.dylib)
2   libsystem_c.dylib               0x0000000197db73a0 _exit :28 (in libsystem_c.dylib)
3   UIKitCore                       0x000000019c2301a4 -[UIApplication _terminateWithStatus:] :508 (in UIKitCore)

Meyers Singleton在多线程场景也时常使用,原来开发中还未遇到异常,为什么现在就出现crash呢?有必要调查一番静态变量的线程安全性。我对IOS不熟悉,算是作为IOS血泪史的开始吧

本文作为一个static变量多线程安全性与跨平台分析总结,为了阅读和行文方便,采用正序从理论定义到编译分析再到数据分析,而实际问题排查过程是逆序的,是根因法路径,用一张形象的图表示这种关系,会有很多旁支没有记录在文中,如果阅读中有疑惑的欢迎联系探讨,很多信息在旁路中没有写入文中。

编译与标准库调查

c++11标准

经过一番调查在c++11的标准文档中发现有对静态变量多线程使用的规范,在 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf, standard 6.7 [stmt.dcl] 的第4节

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

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

CLANG

本机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

构造检测程序

编写测试程序的最终版本如下,此版本是经过了反复调整,力求增大复现问题的概率。

#include<thread>
#include<iostream>
#include<unistd.h>
#define TAG "MY_TEST"
#define MY_DEBUG printf // add your platform timestamp threadid
class Machine
{
public:
    Machine(int year_) : year(year_) {
      MY_DEBUG("before construct Machine:%p, thread:%d, year:%d", this, year_, year);
      MY_DEBUG("after construct Machine:%p, thread:%d, year:%d", this, year_, year);
    }
    ~Machine() {
      MY_DEBUG("before destruct, year:%d", year);
      year = -1;
      MY_DEBUG("after destruct, set -1"); // -1 as invalid static data.
    }
    int GetData() const {
        return year;
    }
    int year;
};

static const Machine golbalMachine(100); // 100 as global static valid data

const Machine &GetMachine(int index)
{
    const static Machine machine(index);
    MY_DEBUG("return object for thread: %d. machine:%p, year:%d, globalMachine:%p, globalYear:%d", index, &machine, machine.GetData(), &golbalMachine, golbalMachine.GetData());
    return machine;
}

void CheckStaticVariable() {
    std::thread t1(GetMachine, 1);
    std::thread t2(GetMachine, 2);
    std::thread t3(GetMachine, 3);

    MY_DEBUG("t1 detach");
    t1.detach();
    MY_DEBUG("t2 detach");
    t2.detach();
    MY_DEBUG("t3 detach");
    t3.detach();
    // MY_DEBUG("t1 join");
    // t1.join();
    // MY_DEBUG("t2 join");
    // t2.join();
    // MY_DEBUG("t3 join");
    // t3.join();
}

int main() {
  MY_DEBUG("start main\n");
  CheckStaticVariable();
  exit(0); // in order to auto complete ios app main thread.
  return 0;
}

linux 平台实测

在Ubuntu机器上用GCC和CLANG两种编译器运行测试。

Description: Ubuntu 20.04.2 LTS

Release: 20.04

g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

clang version 10.0.1

Target: x86_64-unknown-linux-gnu

Thread model: posix

实测

GCC

使用GCC编译器,编译运行上述程序, 在shell中持续循环运行多次,静态变量析构都发生在线程执行完成之后。得到如下结果。GetMachine函数得到的全局、局部静态变量数值都是大于0的有效值,并非-1.

使用fno-threadsafe-statics制造不安全场景, 大规模循环执行后,复现了子线程读取到错误数据的case,此局部静态变量已经析构。由于实验的是简单数据类型, 并没有crash。如果是访问析构后的复杂对象,则可能crash。 而且从多线程发生重复竞争构造同一个静态对象,重复析构同一个静态对象。

同时发现,在大量循环后,全局静态变量始终在子线程访问结束后才析构,与gcc 编译器的说明是对应的,也就是说这个特性一直打开,不受fno-threadsafe-statics影响,此选项只影响局部静态变量。

CLANG

使用 clang编译器,编译运行上述程序, 在shell中持续循环运行多次,静态变量析构都发生在线程执行完成之后。多线程安全。

使用fno-threadsafe-statics制造不安全场景, 大规模循环执行后,可复现了子线程读取到错误数据的case,此局部静态变量已经析构。

汇编分析

为了进一步查看区别和原因,使用GCC编译器编出汇编代码继续分析,使用fno-threadsafe-statics选项得到不安全的汇编代码,对应下图左侧,右侧为静态变量多线程安全代码。将符号demangle后分析差异。

g++ -std=c++11 -pthread -S static_thread.cpp -o static_thread_gcc_x64.S

g++ -std=c++11 -pthread -fno-threadsafe-statics -S static_thread.cpp -o static_thread_gcc_x64_unsafe.S

threadstatic# c++filt _ZGVZ10GetMachineiE7machine

guard variable for GetMachine(int)::machine

threadstatic# c++filt _ZZ10GetMachineiE7machine

GetMachine(int)::machine

threadstatic# c++filt _ZN7MachineC1Ei

Machine::Machine(int)

/threadstatic# c++filt _ZN7MachineD1Ev

Machine::~Machine()

_ZZ10GetMachineiE7machine为 GetMachine(int)::machine 函数调用, _ZN7MachineC1Ei 为Machine类的构造函数。线程安全版本在调用GetMachine时先通过__cxa_guard_acquire获取了guard锁,call _ZN7MachineC1Ei 调用Machine类构造局部静态对象之后,再用__ __cxa_guard_abort 和 __cxa_guard_release 释放锁。最后把析构函数_ZN7MachineD1Ev用__cxa_atexit 注册到程序退出函数表中。

从gcc说明文档也可以看到这个信息:

// The actual code emitted by GCC to call a local static variable's constructor looks something like this:
static <type> guard;

if (!guard.first_byte)
{
    if (__cxa_guard_acquire (&guard))
    {
        bool flag = false;
        try
        {
            // Do initialization.
            __cxa_guard_release (&guard);

            flag = true;
            // Register variable for destruction at end of program.
        }
        catch
        {
            if (!flag)
            {
                __cxa_guard_abort (&guard);
            }
        }
    }
}

在实测部分,大量循环后,全局静态变量始终在子线程访问结束后才析构,说这个特性一直打开,不受fno-threadsafe-statics影响,所以汇编代码无法对比出差异,受时间限制暂未去找实现的原理。

Apple 平台实测

Apple IOS

Clang 12.0.5

保持xcode工程的 Statics are Thread-Safe 选项打开。设定optimization level为-O0,无优化。

手动在iphone XS上运行测试代码,出现下图问题,子线程访问到-1数据时,主线程在调用_exit函数退出,触发_cxa_atexit中注册过的静态变量析构函数。由于实验的是简单数据类型, 并没有crash。如果是访问析构后的复杂对象,则可能crash,正好对应线上crash的场景。

// 线上crash堆栈
Thread 0:
1   libsystem_c.dylib               0x0000000197db7064 __cxa_finalize_ranges :416 (in libsystem_c.dylib)
2   libsystem_c.dylib               0x0000000197db73a0 _exit :28 (in libsystem_c.dylib)
3   UIKitCore                       0x000000019c2301a4 -[UIApplication _terminateWithStatus:] :508 (in UIKitCore)
复制

而linux平台只有关闭线程安全选项fno-threadsafe-statics后才会出现。正常编译下静态变量构造和析构都是安全的。说明此clang+ios并未实现完整的Dynamic Initialization and Destruction with Concurrency.

IOS MNN crash的根源在于Apple clang编译器和运行时库未实现静态变量析构的多线程安全。

Apple Mac

Apple clang version 12.0.5 (clang-1205.0.22.11)

Target: x86_64-apple-darwin20.3.0

Thread model: posix

在mac下使用Apple clang编译,静态变量线程安全选项默认打开情况下,仍然可以复现此问题, 和ios的情况一致。

clang++ -std=c++11 -pthread static_thread.cpp -o static_thread_clang_mac

android平台实测

NDK Clang

Android (7019983 based on r365631c3) clang version 9.0.9 (https://android.googlesource.com/toolchain/llvm-project a2a1e703c0edb03ba29944e529ccbf457742737b) (based on LLVM 9.0.9svn)

Target: x86_64-apple-darwin20.3.0

Thread model: posix

android NDK r21e的clang版本为9.09, 大于了c++11此特性标注的clang 2.9, 编译测试代码,执行可以看到构造过程仍然保证只构造一次, thread1 线程号15623, GetMachine取到的局部和全局静态变量都是-1,因为局部和全局静态变量析构函数已经早于此线程调用GetMachine执行了。此版本析构过程线程不安全。说明此clang+ndk库并未实现完整的 Dynamic Initialization and Destruction with Concurrency.

我手头的ndk版本不高,哪位同学如果有更高版本,方便的话可编译运行一下此测试程序。

aarch64 GCC

Using built-in specs.

COLLECT_GCC=aarch64-linux-gnu-g++

COLLECT_LTO_WRAPPER=/usr/lib/gcc-cross/aarch64-linux-gnu/9/lto-wrapper

Target: aarch64-linux-gnu

Thread model: posix

gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

由于android NDK r18以后已经不再支持GCC编译器,暂且使用GCC arm交叉编译工具 aarch64-linux-gnu-g++ 尝试运行测试程序。在执行后有不兼容的异常, 反复执行多次,构造函数只执行一次,GetMachine日志显示都能得到正确的结果year:1, globalYear:100, 并未出现析构后的-1数值。虽然不完全肯定,初步可以说明 GCC在安卓上静态变量多线程安全

解决办法

虽然c++11标准有约束,但对析构时的多线程和静态变量的关系不是所有编译器和库完整实现,GCC编译器中做了完整实现,实验过的Apple/Android clang编译器版本只支持构造、不支持析构的多线程安全,微软编译器则在VS2015后支持。

追溯解决:** 如要继续追溯析构时的行为差异,不仅是编译器,需要从apple clang编译器代码与std库的某种共同作用着手,这个涉及到一个全新的领域了,暂无法去继续调查,后续暂且给clang或apple提一个issue。

规避解决1: 对于IOS 中遇到的析构时多线程异常问题,虽然本来静态变量并不多,而且语法规范是线程安全的,由于不同厂商编译器和库实现程度不同,MNN又需要做到IOS android linux windows跨平台,我们的解决办法是避免使用static变量或对象,牺牲一些重复创建对象的开销,也要想方设法改成非静态变量 也可以自行加锁,访问、析构前都加锁来避免。

再回到开头的两个经典模式,我们不难发现Meyers Singleton 在gcc编译器下是多线程构造、析构安全的。真是一个表面简单而实际不简单的模式!岁月静好地写代码时有众多大牛思想的结晶在默默守卫。如果要跨平台到IOS上,可要小心了,析构的时候可能发生多线程访问crash。如果自己保证先退出多线程,也是ok的。

Gamma Singleton 构造、析构线程安全吗?它的全局变量是一个指针,简单类型不要调用构造析构。无论哪个编译器和平台。再看构造过程:而多线程调用getInstance时,即使 if判断是原子化的,但m_pInstance = new Singleton() 会多线程竞争创建,并没有实现 the concurrent execution shall wait for completion of the initialization 的特性。所以构造阶段多线程不安全析构阶段:静态变量指针m_pInstance 只是成为释放的内存,多线程读写情况,也有可能变成野指针了!另外开头的示例代码还隐藏一个重要bug, 那就是没有析构对象。所以要自行找到合适的时机,自行加锁、析构Instance。这个单例模式在严格的多线程下问题还不少。

规避解决2: 借助Gamma Singleton,如果保证没有不释放的外部资源,那么我们可以参考gamma singleton构造新的规避方案,不析构释放静态对象,避免多线程不安全,从读者评论里,借鉴到以下非常独特的方法。注意用户一定要保证static对象中不持有一些需要手动释放的资源,例如有的系统连malloc的堆内存都不会析构后自动释放;有的static对象持有的系统设备不会被自动释放;有的则持有跨进程注册的自定义服务不会被自动释放。

//  Thread Safe Singleton

// caution:  this kind of Singleton should not hold any resource that your OS would not auto-release when program went to an end.

class Singleton {
public:
static Singleton& getInstance() {
    static Singleton& instance = *(new Singleton()); // multi-thread safe.
    return instance;
}
private:
    Singleton();
}
// no global static

总结

通过一系列分析和实验、数据分析,找到了IOS MNN crash的根源在于Apple clang编译器和运行时库对c++11 Dynamic Initialization and Destruction with Concurrency特性的支持问题,未实现静态变量析构的多线程安全。得到了多平台的线程安全性和各个影响因素的关系。

  1. 静态变量的多线程访问安全性和c++版本和运行时库、编译器有关,c++11标准standard6.7 [stmt.dcl] 第4节, 3.6.3 Termination [basic.start.term], 要求静态变量构造和析构都要线程安全,实测gcc9.3 (>4.3即可) 已经实现了此特性,称为“Dynamic Initialization and Destruction with Concurrency”。apple clang(12.0.5)编译器只对此特性部分实现,构造阶段实现了,析构阶段未覆盖。需要注意避开。
  2. 静态变量的多线程访问安全性和编译选项-fno-threadsafe-statics 有关,此选项在不同编译器中都默认打开,局部静态变量/对象构造安全性默认可以保证;全局静态变量在主线程中构造,早于调用入口函数,不会被多线程构造。
  1. 静态变量的多线程访问安全性和多线程启动模式有关,即使在第1点中有问题的编译器上,join模式会等待子线程执行完毕后,主线程才继续向下执行,直到静态变量析构,多线程仍然安全,detach模式,打乱先后顺序,则存在风险。
  2. 局部静态变量的多线程访问安全性和调用函数实现形式有关, 如果调用是一个递归函数,则行为未定义。
int foo(int i) {
    // judge
  static int s = foo(2*i); // recursive call - undefined
    return i+1;
}
  1. 静态变量的多线程访问安全性和其构造、析构函数有关,如果是异步构造,则编译器的保护还不够,不足以保护其安全,存在多线程竞争风险, 这也是有的规约不建议构造函数内有异步操作的原因之一,一般把异步调用挪到其成员函数中。如果同步构造,则c++11与GCC编译器的Dynamic Initialization and Destruction with Concurrency特性可以保证构造、析构的多线程安全。

默认选项下,静态变量线程安全性关系表汇总如下,前两行是表头表示编译器和c++版本变量,前四列为四种变量。