Note that there are some explanatory texts on larger screens.

plurals
  1. POQuestion about the usage of CRITICAL_SECTION
    primarykey
    data
    text
    <p>Given the following code,</p> <pre><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; }; </code></pre> <p>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.</p> <p>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?</p> <p>My guess is that somehow the CRITICAL_SECTION has some static flag so that different instances of it can communicate each other.</p> <p>Please correct me if I am wrong.</p> <p>==== Update ====</p> <pre><code>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; }; </code></pre> <p>Thank you</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload