Windows Programming-Critical Section Encapsulation

Source: Internet
Author: User

 

// Method 1: The critsect member variable in lock must be of the reference type.

Class critsect
{
Public:
Friend class lock;
Critsect () {initializecriticalsection (& _ critsection );}
~ Critsect () {deletecriticalsection (& _ critsection );}
PRIVATE:
Void acquire () {entercriticalsection (& _ critsection );}
Void release () {leavecriticalsection (& _ critsection );}

Critical_section _ critsection;
};

Class lock
{
Public:
Lock (critsect & critsect): _ critsect (critsect) {_ critsect. Acquire ();}
~ Lock () {_ critsect. Release ();}
PRIVATE:
Critsect & _ critsect;
};

//
// Method 2 is relatively simple and easy to understand
Class clock {
Public:
CLock () {InitializeCriticalSection (& m_criticalSection );}
Void Lock () {EnterCriticalSection (& m_criticalSection );}
Void Unlock () {LeaveCriticalSection (& m_criticalSection );}
Virtual ~ CLock () {DeleteCriticalSection (& m_criticalSection );}
Private:
CRITICAL_SECTION m_criticalSection;
};


//
Class CScopedLocker {
Public:
CScopedLocker (CLock * t): m_lock (t) {m_lock-> Lock ();}
~ CScopedLocker () {m_lock-> Unlock ();}
Private:
CLock * m_lock;
};

 

 

Note:

1 usage: Define an object with a class and call the function. As follows:
CritSect sect;
Lock lock (sect );
Or
CLock t;
Cscopedlocker ST (& T );

2. However, it seems that these two methods are not the most secure. For details, refer to Article 13 in Objective C ++: Object-based resource management. It is better.

Fangsh

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.