多線程單例模式的安全實現,多線程例模式

來源:互聯網
上載者:User

多線程單例模式的安全實現,多線程例模式

多線程單例模式的實現。通過雙重鎖定,自旋處理,實現安全的多線程單例和共用區資料的訪問。資源訪問的形式採用簡單等待處理.同時使用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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.