Home > front end >  How to check whether a mutex lock have been destroyed or not?
How to check whether a mutex lock have been destroyed or not?

Time:11-10

I have a problem where my code tries to call pthread_mutex_destory() twice. I need to check whether the lock have been destroyed before or not.

How can I do this? Will this work:

void deinit()
{
    if(1 == pthread_mutex_trylock(&this->m_lock))
    {
        (void) pthread_mutex_destroy(&this->m_lock);
    }
}

Will trylock only check weather the mutex is locked or not or will it also show me weather it is deleted or not?

CodePudding user response:

Once you destroy a a c object, the data left behind is garbage. c doesn't let you do this. (It does but you have to explicitly ask for it.) But you are using a c library, so you have to do everything yourself.

So you have a few options:

  • use std::mutex which works nicely with c . But as such, you mutex will have the same lifetime as your containing class. (which is neates)

  • only use pthread_mutex_destroy in your destructor. Same result as above. You mutex is destroyed as you object is destroyed, which happens exactly once.

  • use an std::optional to shield the mutex data if it is not initialized. Wouldn't recommend, as it is an ugly mix of c and c .

  • use a bool to keep track whether you mutex is inited. This is also tricky and ugly as it is prone to mistakes.

I cannot be more specific because i don't know the rest of the code.

  • Related