How to properly remove Mutex?
Usin开发者_运维问答g 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
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.
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.
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.
精彩评论