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() {}
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM