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

C++/CLI 實作 Singleton 模式:雙重檢查鎖定最佳實踐

     編輯:關於C++

雙重檢查鎖定

Singleton 模式在多執行緒環境中具高價值。ACE 框架大量使用 ACE_Singleton 模板將一般類別轉為 Singleton 行為,優化後效能較標準互斥版本提升 15 倍。C++/CLI 實作同樣不可或缺。

完整程式碼實作

#pragma once

/** \class sidle::Singleton
    \brief Singleton (Double-Checked Locking)
    \author 吳爾平
    \version 1.0
    \date 2005.02.08
*/
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();
    }; // ref class Singleton
}; // namespace sidle

關鍵點解析

  • 泛型模板:template<typename _T> ref class Singleton 可套用至任意參考型別。
  • 雙重檢查:第一次 nullptr 檢查避免不必要鎖定開銷;進入鎖定後第二次檢查確保單一實例化。
  • Mutex 同步:WaitOne()/ReleaseMutex() 確保執行緒安全,finally 區塊保證釋放。
  • 受保護建構函式:Singleton() {} 防止外部直接實例化。
  • 靜態欄位初始化:_mut = gcnew Mutex() 於類別載入時建立,執行緒安全。

使用範例

ref class MyService { /* ... */ };
MyService^ svc = sidle::Singleton<MyService>::Instance();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved