C++????????????д???????????
???????????? ???????[ 2015/1/13 13:51:49 ] ????????C++ ????? net
?????????λ???????????????е???????????????????????????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???????????????????
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11