Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is pseudo-code for how I would do it. I am assuming the existing of a <code>mutex</code> class with <code>lock()</code> and <code>unlock()</code> operations.</p> <pre><code>// This forward declaration helps with declaration // of the "friend" status for the nested class. class DoItOnce; class DoItOnce { private: bool m_amFirst; mutex m_mutex; friend class ::DoItOnce::Op; public: DoItOnce() { m_amFirst = true; init(m_mutex); } ~DoItOnce() { destroy(m_mutex); } void reset() { m_mutex.lock(); m_amFirst = true; m_mutex.lock(); } //-------- // Nested class //-------- class Op { public: Op(DoItOnce &amp; sync) : m_sync(sync) { m_sync.m_mutex.lock(); m_amFirst = m_sync.m_amFirst; m_sync.m_amFirst = false; } ~Op() { m_sync.m_mutex.unlock(); } bool amFirst() { return m_amFirst; } private: DoItOnce &amp; m_sync; bool m_amFirst; }; // end of nested class }; // end of outer class </code></pre> <p>Here is an example to illustrate its intended use. You will implement the <code>doWork()</code> operation and have all your threads invoke it.</p> <pre><code>class WorkToBeDoneOnce { private: DoItOnce m_sync; public: bool doWork() { DoItOnce::Op scopedLock(m_sync); if (!scopedLock.amFirst()) { // The work has already been done. return true; } ... // Do the work return true; } void resetAmFirstFlag() { m_sync.reset(); } } </code></pre> <p>If you are confused by my use of the <code>DoItOnce::Op</code> nested class, then you can find an explanation of this coding idiom in my <em>Generic Synchronisation Policies</em> paper, which is available <a href="http://www.ciaranmchale.com/training-courses.html#training-gsp" rel="nofollow">here</a> in various formats (HTML, PDF and slides).</p>
    singulars
    1. This table or related slice is empty.
    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.
    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