多線程單例模式的安全實現,多線程例模式
多線程單例模式的實現。通過雙重鎖定,自旋處理,實現安全的多線程單例和共用區資料的訪問。資源訪問的形式採用簡單等待處理.同時使用std::bind進行函數綁定。
// atomic_lock_flag_p202_6-3-3.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <atomic>#include <iostream>#include <thread>#include <Windows.h>#include <vector>using std::cout;using std::cin;using std::endl;std::atomic_flag lock = ATOMIC_FLAG_INIT;class TestLockInit{public:TestLockInit();~TestLockInit();static TestLockInit * TestLockInit::getInstance(void);void display(void){//自旋嘗試加鎖while (lock.test_and_set(std::memory_order_acquire)){}cout<<"-----"<<++i<<endl;//釋放互斥鎖lock.clear(std::memory_order_release);}private:static TestLockInit * s_pTestLockInit;static std::atomic_flag lock;std::atomic<int>i;};TestLockInit * TestLockInit::s_pTestLockInit = nullptr;std::atomic_flag TestLockInit::lock = ATOMIC_FLAG_INIT;TestLockInit * TestLockInit::getInstance(void){if (s_pTestLockInit==nullptr){//自旋嘗試加鎖while (lock.test_and_set(std::memory_order_acquire)){cout<<"??????????????"<<endl;}//執行初始化if (s_pTestLockInit==nullptr){s_pTestLockInit = new TestLockInit();}//釋放互斥鎖lock.clear(std::memory_order_release);}return s_pTestLockInit;}TestLockInit::TestLockInit():i(10){}TestLockInit::~TestLockInit(){}void f(int n){while (lock.test_and_set(std::memory_order_acquire)){std::cout<<"Waiting from thread "<<n<<std::endl;}cout<< "Thred "<< n << " Starts working"<<endl;TestLockInit::getInstance()->display();}void g(int n){cout<< "Thread "<<n<< " is going to start."<<endl;lock.clear();cout<< "Thread "<<n<<" Starts working" <<endl;TestLockInit::getInstance()->display();}void h(void){auto a = std::bind(&TestLockInit::display,TestLockInit::getInstance());a();}int _tmain(int argc, _TCHAR* argv[]){lock.test_and_set();//設為預設狀態;/*std::thread t1(f,1);std::thread t2(g,2);t1.join();Sleep(100);t2.join();*/std::vector<std::thread> vthread;for (int i = 0; i < 10; ++i){vthread.push_back(std::move(std::thread(h)));}for(std::thread & th :vthread){th.join();}return 0;}