1. 程式人生 > 實用技巧 >C++11中靜態區域性變數初始化的執行緒安全性

C++11中靜態區域性變數初始化的執行緒安全性

在C++標準中,是這樣描述的(在標準草案的6.7節中):

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

分析

標準關於區域性靜態變數初始化,有這麼幾點要求:

  1. 變數在程式碼第一次執行到變數宣告的地方時初始化。
  2. 初始化過程中發生異常的話視為未完成初始化,未完成初始化的話,需要下次有程式碼執行到相同位置時再次初始化。
  3. 在當前執行緒執行到需要初始化變數的地方時,如果有其他執行緒正在初始化該變數,則阻塞當前執行緒,直到初始化完成為止。
  4. 如果初始化過程中發生了對初始化的遞迴呼叫,則視為未定義行為

所以一下這種方式,直接就是執行緒安全的

class Foo
{
public:
    static Foo *getInstance()
    {
        static Foo s_instance;
        
return &s_instance; } private: Foo() {} };