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;
}

 

輸出結果ios

 

build Test 3begin
build Test 3end
0x7fe1480008c0end
0x7fe1480008c0end
0x7fe1480008c0end函數

構造函數只被調用了一次,靜態代碼快構造函數只能有一個線程訪問。ui

相關文章
相關標籤/搜索