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?
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).
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.
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.
Yes, it is a blocking call and will block until it gets the lock.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With