+ Reply to Thread
Results 1 to 2 of 2

Thread: Is there ready made class for CRITICAL_SECTION for data safety?

  1. #1
    Senior Member
    Join Date
    Feb 2012
    Posts
    109

    Is there ready made class for CRITICAL_SECTION for data safety?

    Hi All,

    I want to have a ready made wrapper class for CRITICAL_SECTION.

    Thanks in advance.

    Regards,
    Red

  2. #2
    Junior Member
    Join Date
    Feb 2012
    Posts
    49
    Hi Red,

    Please see the below code snippet:

    Code:
    class CMyAutoCriticalSection
    {
    private:
    	CRITICAL_SECTION m_objCriticalSection ;
    
    	CMyAutoCriticalSection* operator =(const CMyAutoCriticalSection&) {}
    	CMyAutoCriticalSection(const CMyAutoCriticalSection&) ;
    public:
    
    	CMyAutoCriticalSection(const CRITICAL_SECTION& objCriticalSection)
    	{
    		m_objCriticalSection = objCriticalSection ;
    		EnterCriticalSection(&m_objCriticalSection) ;
    	}
    
    	~CMyAutoCriticalSection()
    	{
    		LeaveCriticalSection(&m_objCriticalSection) ;
    	}
    } ;
    
    class CAutoCriticalSectionClient
    {
    private:
    
    	CRITICAL_SECTION m_objCriticalSection ;
    
    	int m_nSharedData ;
    	
    public:
    
    	CAutoCriticalSectionClient()
    	{
    		IntializeCS() ;
    		m_nSharedData = 0 ;
    	}
    
    	~CAutoCriticalSectionClient()
    	{
    		m_nSharedData = 0 ;
    		DeintializeCS() ;
    	}
    
    	IntializeCS() ;
    
    	DeintializeCS() ;
    
    	int IncrementSharedData() ;
    
    	int DecrementSharedData() ;
    } ;
    
    CAutoCriticalSectionClient::IntializeCS()
    {
    	InitializeCriticalSection(&m_objCriticalSection) ;
    }
    
    CAutoCriticalSectionClient:: DeintializeCS()
    {
    	DeleteCriticalSection(&m_objCriticalSection) ;
    }
    
    int CAutoCriticalSectionClient::IncrementSharedData()
    {
    	CMyAutoCriticalSection objMyAutoCriticalSection(m_objCriticalSection) ;
    
    	return m_nSharedData++ ;
    }
    
    int CAutoCriticalSectionClient:: DecrementSharedData()
    {
    	CMyAutoCriticalSection objMyAutoCriticalSection(m_objCriticalSection) ;
    
    	return m_nSharedData--  ;
    }
    
    void UseCriticalSection()
    {
    	CAutoCriticalSectionClient objAutoCriticalSectionClient ;
    
    	objAutoCriticalSectionClient.IncrementSharedData() ;
    
    	objAutoCriticalSectionClient.DecrementSharedData() ;
    }
    Hope this will help.

    Regards.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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