首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++/CLI 實現 Singleton 模式:雙重檢查鎖定優化

     編輯:VC 教學

雙重檢查鎖定在多執行緒 Singleton 實現中價值高。ACE 以 ACE_Singleton 模板廣泛應用,優化後性能較標準互斥提升 15 倍。C++/CLI 環境下同樣需要,以下為實現代碼。

實現代碼

#pragma once

namespace sidle {
using namespace System;
using namespace System::Threading;

template<typename _T>
ref class Singleton {
public:
    static _T^ Instance() {
        if (_instance == nullptr) {
            _mut->WaitOne();
            try {
                if (_instance == nullptr) {
                    _instance = gcnew _T();
                }
            }
            finally {
                _mut->ReleaseMutex();
            }
        }
        return _instance;
    }
protected:
    Singleton() {}
    static _T^ _instance;
    static Mutex^ _mut = gcnew Mutex();
};
} // namespace sidle

關鍵點

  • 使用 Mutex 實現線程同步。
  • 雙重 nullptr 檢查減少鎖爭用,提升效能。
  • try/finally 確保鎖釋放。
  • 建構子 protected 防止外部實例化。
  • 泛型 _T 支援任意參考類型。

使用範例

ref class MyService { ... };
MyService^ svc = sidle::Singleton<MyService>::Instance();

此實現消除重複代碼,提供高效能線程安全 Singleton,適合 C++/CLI 專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved