I need to create a mutex inside the body of a thread dynamically and map it to a structure so that other threads can use it.
What I'm doing is
pthread_mutex_t* p = new pthread_mutex_t;
*p = PTHREAD_MUTEX_INITIALIZER;
Then, when all threads are done with the mutex, I run
pthread_mutex_destroy(p);
Now, this works fine. However, if I also attempt to
delete p;
after the destroy call, I get SIGSEGV signals every time.
My questions are:
- Is it ok to initialize the dynamically allocated mutex this way, can it lead to UB? Should I use
pthread_mutex_initinstead of the 'flag'? - Is
pthread_mutex_destroyenough in the case of this dynamically allocated mutex or should Ideleteit instead, in order to avoid memory leaks? Doing both seems to be an issue.
Also I know I'm mixing the C API with C++ in this case, but I kinda have to do it right now.
Thanks in advance.