Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to lock a pthread mutex before destroying it? [duplicate]

Tags:

c++

pthreads

class AAA
{
    ...
    ~AAA()
    {
        pthread_mutex_lock( &m_mutex );
        pthread_mutex_destroy( &m_mutex );
    }
}

Question> I saw this code somewhere in a project. Is it good practice to do so? Or it is undefined behavior to lock a mutex before destroying it?

like image 382
q0987 Avatar asked Nov 07 '14 19:11

q0987


People also ask

When should you destroy mutex?

Destroying Mutexes Implementations are required to allow an object to be destroyed and freed and potentially unmapped (for example, lines A and B) immediately after the object is unlocked (line C).

Is it necessary to destroy mutex?

Like any system resource that can be shared among threads, a mutex allocated on a thread's stack must be destroyed before the thread is terminated) actually does explicitly state this in their documentation.

What happens if you try to lock a locked mutex?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

Is Pthread mutex lock blocking?

Yes, it is a blocking call and will block until it gets the lock.


2 Answers

It strikes me as utterly terrible practice.

from http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_destroy.html

It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex results in undefined behavior.

so this code guarantees undefined behavior and needs to be fixed.

like image 157
camelccc Avatar answered Oct 17 '22 10:10

camelccc


This link says its undefined behavior.

Maybe from where you saw this code, the original coder wanted to destroy the mutex and might have thought that if he/she would be able to lock that mutex, then that means it's unlocked somewhere else by some important thread, and thus he can delete it.

But it's implemented incorrectly.

like image 6
Rupesh Yadav. Avatar answered Oct 17 '22 10:10

Rupesh Yadav.