C++/CLI singleton模式 (雙重檢測鎖實現)

來源:互聯網
上載者:User

    雙重檢測鎖(Double-Checked Locking)實現的Singleton模式在多線程應用中有相當的價值。在ACE的實現中就大量使用ACE_Singleton模板類將普通類轉換成具有Singleton行為的類。這種方式很好地消除了一些重複代碼臭味,而且,最佳化後的效能較標準互斥版本提高15倍[1]。最近在用C++/CLI做一些工作,Singleton不可避免地需要用到,於是我又製造了一次車輪 ^_^

 1 #pragma once
 2 
 3 /** \class sidle::Singleton
 4    \brief Singleton (Double-Checked Locking)
 5    \author 吳爾平
 6    \version 1.0
 7    \date 2005.02.08 - 
 8    \bug 
 9    \warning
10 */
11 
12 namespace sidle
13 {
14     using namespace System;
15     using namespace System::Threading;
16 
17     template<typename _T> 
18     ref class Singleton 
19     {
20     public:
21         static _T^ Instance()
22         {
23             if (_instance == nullptr)
24             {
25                 _mut->WaitOne();
26                 try
27                 {
28                     if (_instance == nullptr)
29                     {
30                         _instance = gcnew _T();
31                     }
32                 }
33                 finally
34                 {
35                     _mut->ReleaseMutex();
36                 }
37             }
38             return _instance;
39         }
40     protected:
41         Singleton(){}
42         static _T^ _instance;
43         static Mutex^ _mut = gcnew Mutex();
44     }; // ref class Singleton 
45 
46 }; // namespace sidle 

參考文獻:
[1] PATTERN LANGUAGES OF PROGRAM DESIGN 3  (Robert C. Martin...)
        VII. PROGRAMMING PATTERNS. 
                20. Double-Checked Locking, Douglas E. Schmidt and Tim Harrison.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.