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.
Couldn’t you just do:
assuming counter is initialized to 0 before either thread starts, of course.