Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your update is no better. If you want to do this in an RAII style then you need to work a bit harder. The key is that you need to separate the critical section object which is statically allocated, and the lock which is local to all blocks that need protection.</p> <p>The following is lifted from <a href="http://jrdodds.blogs.com/blog/2004/08/raii_in_c.html" rel="noreferrer">Jonathan Dodds</a> but it is a classic pattern.</p> <pre><code>class CriticalSection { public: CriticalSection() { ::InitializeCriticalSection(&amp;m_rep); } ~CriticalSection() { ::DeleteCriticalSection(&amp;m_rep); } void Enter() { ::EnterCriticalSection(&amp;m_rep); } void Leave() { ::LeaveCriticalSection(&amp;m_rep); } private: // copy ops are private to prevent copying CriticalSection(const CriticalSection&amp;); CriticalSection&amp; operator=(const CriticalSection&amp;); CRITICAL_SECTION m_rep; }; </code></pre> <p>Whilst you could do this with inheritance of CRITICAL_SECTION, I feel encapsulation is more appropriate. </p> <p>Next the lock is defined:</p> <pre><code>class CSLock { public: CSLock(CriticalSection&amp; a_section) : m_section(a_section) { m_section.Enter(); } ~CSLock() { m_section.Leave(); } private: // copy ops are private to prevent copying CSLock(const CSLock&amp;); CSLock&amp; operator=(const CSLock&amp;); CriticalSection&amp; m_section; }; </code></pre> <p>Finally, an example of usage:</p> <pre><code>class Example { public: bool Process( … ); … private: CriticalSection m_criticalsection; … }; bool Example::Process( … ) { CSLock lock(m_critsection); // do some stuff … } </code></pre> <p>The point is that there is a single instance of the critical section, shared across all threads. This is what makes a critical section work.</p> <p>In counterpoint, there may be many instances of <code>CSLock</code>, all taken on the same critical section, in simultaneous existence. This allows the <code>Process()</code> method to be called by many threads, but have its code is serialized over the lifetime of the <code>CSLock</code> instance taken on the single shared critical section.</p>
 

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