Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an approach I've successfully used in the past:</p> <p>Implement your "completion" task as a reference counted object. Each worker thread holds a reference to this object while it is doing its work, then releases it when finished. The completion task does its work when the ref count reaches 0.</p> <h2>Example</h2> <p><em>Note: my C++ is rusty after years of working primarily in C#, so treat the example below as pseudo-code</em></p> <h2>Completion Task</h2> <pre><code>class MyCompletionTask { private: long _refCount; public: MyCompletionTask() { _refCount = 0; } public: // Reference counting implementation // Note ref-counting mechanism must be thread-safe, // so we use the Interlocked functions. void AddRef() { InterlockedIncrement(&amp;_refCount); } void Release() { long newCount = InterlockedDecrement(&amp;_refCount); if (newCount == 0) { DoCompletionTask(); delete this; } } private: void DoCompletionTask() { // TODO: Do your thing here } } </code></pre> <h2>Calling Code</h2> <pre><code>MyCompletionTask *task = new MyCompletionTask(); task-&gt;AddRef(); // add a reference for the main thread for( &lt;loop thru some items &gt;) { task-&gt;AddRef(); // Add a reference on behalf of the worker // thread. The worker thread is responsible // for releasing when it is done. QueueUserWorkItem(ThreadProc, (PVOID)task, &lt;etc&gt; ); } task-&gt;Release(); // release main thread reference // Note: this thread can exit. The completion task will run // on the thread that does the last Release. </code></pre> <h2>Thread Proc</h2> <pre><code>void ThreadProc(void *context) { MyCompletionTask *task = (MyCompletionTask)context; // TODO: Do your thing here task-&gt;Release(); } </code></pre> <p>One thing to keep in mind with this approach is that the thread on which the completion task completes is non-deterministic. It will depend on which worker thread finishes first (or the main thread, if all the worker threads finish before the main thread calls Release)</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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