Note that there are some explanatory texts on larger screens.

plurals
  1. POThread-Safe implementation of an object that deletes itself
    primarykey
    data
    text
    <p>I have an object that is called from two different threads and after it was called by both it destroys itself by "delete this".</p> <p>How do I implement this thread-safe? Thread-safe means that the object never destroys itself exactly one time (it must destroys itself after the second callback).</p> <p>I created some example code:</p> <pre><code>class IThreadCallBack { virtual void CallBack(int) = 0; }; class M: public IThreadCallBack { private: bool t1_finished, t2_finished; public: M(): t1_finished(false), t2_finished(false) { startMyThread(this, 1); startMyThread(this, 2); } void CallBack(int id) { if (id == 1) { t1_finished = true; } else { t2_finished = true; } if (t1_finished &amp;&amp; t2_finished) { delete this; } } }; int main(int argc, char **argv) { M* MObj = new M(); while(true); } </code></pre> <p>Obviously I can't use a Mutex as member of the object and lock the delete, because this would also delete the Mutex. On the other hand, if I set a "toBeDeleted"-flag inside a mutex-protected area, where the finised-flag is set, I feel unsure if there are situations possible where the object isnt deleted at all. Note that the thread-implementation makes sure that the callback method is called exactly one time per thread in any case.</p> <p>Edit / Update: What if I change Callback(..) to:</p> <pre><code>void CallBack(int id) { mMutex.Obtain() if (id == 1) { t1_finished = true; } else { t2_finished = true; } bool both_finished = (t1_finished &amp;&amp; t2_finished); mMutex.Release(); if (both_finished) { delete this; } } </code></pre> <p>Can this considered to be safe? (with mMutex being a member of the m class?)</p> <p>I think it is, if I don't access any member after releasing the mutex?!</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