1. 程式人生 > >c++靜態程式碼實現多執行緒安全的單例模式

c++靜態程式碼實現多執行緒安全的單例模式

開發十年,就只剩下這套架構體系了! >>>   

#include "boost/shared_ptr.hpp"
#include "iostream"
#include "boost/thread.hpp"

class Test {

private:
    Test(int n) {
        std::cout << "build Test " << n << "begin"<<std::endl;
        sleep(n);
        std::cout << "build Test " << n << "end"<<std::endl;
    }
public:


    static boost::shared_ptr<Test> getTest(int n) {
        static boost::shared_ptr<Test> instance = boost::shared_ptr<Test>(new Test(n));
        std::cout << static_cast<const void *>(instance.get()) << "end"<<std::endl;
        return instance;
    }
};

int main() {

    boost::thread th1([]() {
        auto t1 = Test::getTest(3);
    });
    th1.join();
    boost::thread th2([]() {
        auto t2 = Test::getTest(2);
    });
    th2.join();
    boost::thread th3([]() {
        auto t3 = Test::getTest(1);
    });
    th3.join();
    return 1;
}

 

輸出結果

 

build Test 3begin
build Test 3end
0x7fe1480008c0end
0x7fe1480008c0end
0x7fe1480008c0end

建構函式只被呼叫了一次,靜態程式碼快建構函式只能有一