Quantcast
Channel: Question about the usage of CRITICAL_SECTION - Stack Overflow
Viewing all articles
Browse latest Browse all 6

Question about the usage of CRITICAL_SECTION

$
0
0

Given the following code,

class MyCriticalSection : protected CRITICAL_SECTION{public:    MyCriticalSection()    {        InitializeCriticalSection(this);        EnterCriticalSection(this);    }    ~MyCriticalSection()    {        LeaveCriticalSection(this);        DeleteCriticalSection(this);    }};class MyClass{public:    MyClass() : m_Int(0) {}    int GetNum()     {         MyCriticalSection myCriticalSectionA;  // LockA        return m_Int;     }    int SetNum(int i)    {        MyCriticalSection myCriticalSectionB;  // LockB        m_Int = i;    }protected:    int m_Int;};

I assume that the above design is correct, please correct me if you find some errors.The usage of LockA has two capabilities: 1> it prevents the function GetNum from being call at the same time by more than one thread. 2> it prevents the functions GetNum and SetNum from accessing the m_Int at the same time.

Here is my question:The variables myCriticalSectionA and myCriticalSectionB are two different instances of class MyCriticalSection. Why they can collaborate with each other so that the lock mechanism work as expect?

My guess is that somehow the CRITICAL_SECTION has some static flag so that different instances of it can communicate each other.

Please correct me if I am wrong.

==== Update ====

class MyCriticalSection : protected CRITICAL_SECTION{public:    MyCriticalSection()    {        InitializeCriticalSection(this);    }    ~MyCriticalSection()    {               DeleteCriticalSection(this);    }    void Lock()    {        EnterCriticalSection(this);    }    void UnLock()    {        LeaveCriticalSection(this);    }};class MyClass{public:    MyClass() : m_Int(0) {}    int GetNum()     {         m_Lock.Lock();        // do something here        m_Lock.UnLock();        return m_Int;     }    int SetNum(int i)    {        m_Lock.Lock();              m_Int = i;        m_Lock.UnLock();    }protected:    int m_Int;    MyCriticalSection m_Lock;};

Thank you


Viewing all articles
Browse latest Browse all 6

Latest Images

Trending Articles





Latest Images