Search code examples
clinuxsynchronizationpthreadsmutex

In C language, do pthread_mutex_t need to be released after use?


I use pthread_mutex_t in my program for thread synchronization control.
Do I need to do some finishing works when the pthread_mutex_t is no longer in use?
Or, can I do nothing?

Thank you for your help


Solution

  • You mention that "the pthread_mutex_t is no longer in use".
    I assume you mean that you no longer need to use it, ever, in any of your threads.

    In this case:

    1. The pthread_mutex_t must be in the unlocked state.
    2. You should call pthread_mutex_destroy.

    The requirement for the mutex to be unlocked appears in the documentation for pthread_mutex_destroy:

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

    (emphasis is mine)

    This post contains some more info about the proper usage of pthread_mutex_destroy:
    How to safely and correctly destroy a mutex in Linux using pthread_mutex_destroy?.