雙重檢查鎖定在多執行緒 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 專案。