?????????λ???????????????е???????????????????????????C++???????????????д???′???

 

1 class CSingleton
2 {
3 private:
4     CSingleton() //??????????е?
5     {
6     }
7     static CSingleton *m_pInstance;
8 public:
9     static CSingleton * GetInstance()
10     {
11         if (m_pInstance == NULL) //?ж???????ε???
12             m_pInstance = new CSingleton();
13         return m_pInstance;
14     }
15 };

??????????????????????????????????????????????????????????????????race condition???????????????????????????????????????????????????????????????????????shared data????????????????μ???????????????????????

 

1 class CSingleton
2 {
3 private:
4     CSingleton() //??????????е?
5     {
6     }
7     static CSingleton *m_pInstance;
8     mutex mtx;
9 public:
10     static CSingleton * GetInstance()
11     {
12         mtx.lock();
13         if (m_pInstance == NULL) //?ж???????ε???
14             m_pInstance = new CSingleton();
15         mtx.unlock();
16         return m_pInstance;
17     }
18 };

???????????????????????ε???GetInstance??????????????????????????heavy contention????o???????????????????????????????????????????????ε???GetInstance????????????????????????new????????????????????????????????????????DCL????????Double Check Lock?????????£?

 

1 Widget* Widget::pInstance{ nullptr };
2 Widget* Widget::Instance() {
3     if (pInstance == nullptr) { // 1: first check
4         lock_guard<mutex> lock{ mutW };
5         if (pInstance == nullptr) { // 2: second check
6             pInstance = new Widget();
7         }
8     }
9     return pInstance;
10 }

??????????????????δ??????????????????????????????????????????е?bug????????????????????????????????????????????????????????????????memory model??????????????????????仰???????????е????д???if (pInstance == nullptr)??????д???pInstance = new Widget();???????????????????????????new?????????????pInstance??????Widget???????й????????????????????????е?????????????????if?????????????????????????????????????????????C++11??г????????????????????memory barrier????????????????C++11?????????ü????????????????????????????memory model?????C++11???????????????????