萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++/CLI 實現線程安全 Singleton:雙重檢查鎖定模式

設計目標

  • 線程安全:多線程並發首次訪問僅創建一次實例。
  • 高性能:避免每次訪問都加鎖(雙重檢查)。
  • 泛型復用:模板化支援任意引用類型 _T。
  • CLI 原生:使用 System::Threading::Mutex,無需 P/Invoke。

完整實現代碼

#pragma once

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

    generic <typename _T> where _T : ref class
    public 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() {}                          // 防止外部實例化

    private:
        static _T^ _instance = nullptr;
        static Mutex^ _mut = gcnew Mutex();     // 進程級互斥體,跨 AppDomain 也安全
    };
}

關鍵點解析

要點說明
generic <typename _T> where _T : ref classCLI 泛型約束:_T 必須為引用類型(ref class),值類型無法為 null。
_mut->WaitOne() / ReleaseMutex()CLI 互斥體,比 Monitor 更重但支援跨進程同步;此處用於確保進程內線程安全即可。
try/finally保證鎖在異常時釋放,避免死鎖。
靜態構造函數替代方案CLI 靜態構造函數由 CLR 保證線程安全且僅執行一次,若無延遲初始化需求,直接 static _T^ _instance = gcnew _T(); 更簡潔。

使用範例

ref class ConfigManager {
public:
    property String^ ConnectionString;
    ConfigManager() { ConnectionString = "Server=..."; }
};

// 客戶端代碼
ConfigManager^ cfg = Singleton<ConfigManager>::Instance();
Console::WriteLine(cfg->ConnectionString);

與 C++ 原生 Singleton 對比

  • C++11 靜態局部變數:static T& instance() { static T inst; return inst; }(魔術靜態,無鎖線程安全)。
  • C++/CLI 無魔術靜態保證,需顯式鎖或靜態構造函數。
  • CLI Mutex 開銷大於 Monitor(lock),高頻訪問場景可改用 Monitor::Enter/Exit。

擴展:支援參數化構造

static _T^ Instance(array<Object^>^ args) {
    if (_instance == nullptr) {
        _mut->WaitOne();
        try {
            if (_instance == nullptr) {
                _instance = (_T^)Activator::CreateInstance(_T::typeid, args);
            }
        } finally { _mut->ReleaseMutex(); }
    }
    return _instance;
}
copyright © 萬盛學電腦網 all rights reserved