3

Using C++, in one of my destructors, i say

mutex = NULL;

This however results in an error "No viable overloaded '='" in my Xcode.

Same mutex was previously initialized in a constructor as

mutex = PTHREAD_MUTEX_INITIALIZER;

Please advise, how can i properly handle this as part of C++ destructor

Translucent Pain
  • 1,441
  • 2
  • 14
  • 18
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

3 Answers3

5

You may use pthread_mutex_destroy() to destroy the mutex object.

According to the POSIX specification:

The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

CRM
  • 4,569
  • 4
  • 27
  • 33
3

It is not necessary to use pthread_mutex_destroy on a staticly allocated mutex. If your mutex is allocated on the stack or heap you should be using pthread_mutex_init and pthread_mutex_destroy. And most importantly make sure the mutex is unlocked before destruction.

Duck
  • 26,924
  • 5
  • 64
  • 92
2

As bacchus said, use pthread_mutex_destroy(). If the mutex is a member of a C++ class, I wonder why you initialized it with PTHREAD_MUTEX_INITIALIZER, rather than using pthread_mutex_init(), as the macro form is more suited for initialization rather than assignment.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185