title: Delete an object securely from a multi-threaded program
body: <p><strong>DISCLAIMER: neither Boost, nor C++11 allowed.</strong></p>
  
  <p>I've a program, in which I create an instance of <code>Foo</code> and I operate with it in a number of threads. Then I want to delete it securely so those threads do not fall into a segmentation fault.</p>
  
  <p>I've added a mutex member to <code>Foo</code> and lock it each time a thread function runs. In order different threads do not conflict with each other.</p>
  
  <pre><code>class Foo
  {
      public:
          pthread_mutex_t mutex;
  };
  
  void* thread ( void* fooPtr )
  {
      Foo* fooPointer = (Foo*) fooPtr;
  
      while ( 1 )
      {
          if ( fooPointer )
          {
              pthread_mutex_lock ( &amp;fooPointer-&gt;mutex );
              /* some code, involving fooPointer */
              pthread_mutex_unlock ( &amp;fooPointer-&gt;mutex );
          }
          else
          {
              pthread_exit ( NULL );
          }
      }
  }
  </code></pre>
  
  <p>Now I want to delete <code>foo</code> securely so no errors occur in threads. I've added a destructor to <code>Foo</code>:</p>
  
  <pre><code>Foo::~Foo()
  {
      pthread_mutex_lock ( &amp;mutex );
  }
  </code></pre>
  
  <p>Now the object will not be deleted until all threads finish current loop.</p>
  
  <p>The question is: will the mutex be unlocked after an instance is deleted? Will all the threads finish after an instance is deleted? I bet the answer is <code>no</code>. So I change the destructor, but now it seems thread-unsafe:</p>
  
  <pre><code>Foo::~Foo()
  {
      pthread_mutex_lock ( &amp;mutex );
      pthread_mutex_unlock ( &amp;mutex );
  }
  </code></pre>
  
  <p>Can the thread function lock the mutex and start operating the instance after <code>pthread_mutex_unlock ( &amp;mutex );</code> and BEFORE the object is deleted?</p>