Ads
Contact
This form does not yet contain any fields.
    RSS
    Search
    Social Links
    Navigation
    Powered by Squarespace
    Twitter
    Instagram

    Entries in programming (1)

    Thursday
    Nov052009

    Different Types of pthread_mutex_t Types

    When working Linux with a pthread_mutex_t, it's fun to note that there are different types of mutexes.  From the man pages:

    If the mutex type is PTHREAD_MUTEX_NORMAL, deadlock detection is not provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behaviour results.

    If the mutex type is PTHREAD_MUTEX_ERRORCHECK, then error checking is provided. If a thread attempts to relock a mutex that it has already locked, an error will be returned. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.

    If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex maintains the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count is set to one. Every time a thread relocks this mutex, the lock count is incremented by one. Each time the thread unlocks the mutex, the lock count is decremented by one. When the lock count reaches zero, the mutex becomes available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.

    If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behaviour. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behaviour. Attempting to unlock the mutex if it is not locked results in undefined behaviour.

    I'd like to focus on the the two items that I highlighted in bold above.

    At first glance, some people might look at PTHREAD_MUTEX_NORMAL, and see that as the most satisfactory setting on a mutex: You lock it once, and then unlock it when you're done.  But what some people don't take into account is that a mutex may be locked before calling another function that locks the same mutex, but can be called from a location where the mutex isn't already locked.  In this sense, making it a recursive mutex - as described above, a mutex that can have lock called multiple times from one thread, and then safely released multiple times from the same thread - would be the best approach.

    Have fun with your mutexes!

    L8r
    Paul