Q:

Synchronize 2 posix threads

I have 2 threads and both of them are deleting memory at the end nedded by both. My problem is that maybe it can happen that a thread start and finish before the other one starts and so it deletes the memory nedded by the other thread. How can I synchronize them so that this can't happend.
As a design my threads look like this:  
void* thread1(void* arg)   
{
   lock(&mutex);
   counter++;
   unlock(&mutex);

   // more code here

   lock(&mutex);
   counter--;
   if(counter == 0)
   {  
      delete a;
      delete b;
    }
    unlock(&mutex);
}

The other thread looks the same, but this isn't unoff to stop thread1 to finish before thread2 starts.
Thanks.

A:

Couldn't you just do:
void *thread1(void* arg)
{
   // your code

   lock(&mutex);
   counter++;
   if (counter == 2) {
      // whatever
   }
   unlock(&mutex);
}

assuming counter is initialized to 0 before either thread starts, of course.

