CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Threaded View

  1. #1
    Join Date
    Dec 2005
    Posts
    445

    Where to initialize CRITICAL_SECTION in a singleton?

    Hi all,

    I want to use a CRITICAL_SECTION in my singleton class to synchronize access by multiple threads.

    I need to lock the singleton even after initialization so the double checked lock perils are not an issue for me.

    What I don't unserstand is where do I need to initialize my critical section?

    Can someone show me in the following code where InitilalizeCriticalSection() needs to be used?

    Code:
    class CSingleton
    {
    private:
        static CRITICAL_SECTION m_cs;
        static CSingleton *pInstance;
    
        CSingleton();
        CSingleton(const CSingleton&);
        CSingleton&  operator=(const CSingleton&);
        
    public:  
        static CSingleton& Instance(); 
    };
    
    Singleton* CSingleton::pInstance = NULL;
    Singleton* CSingleton::m_cs = 0;
    
    Singleton* Singleton::Instance()
    {
        EnterCriticalSection(&m_cs); // To simplify I'm not using raii guard
    	
        if ( !pInstance )
            pInstance = new CSingleton;
      
        // Do stuff............
    
        LeaveCriticalSection(&m_cs);
        return *pInstance;
    }

    Many thanks!!!!
    Last edited by Salvadoravi; October 10th, 2009 at 07:48 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured