3
votes

https://stackoverflow.com/a/189778/462608

In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex.

What I have studied about Mutexes is that a thread acquires it when it wants to do something to a shared object, and when it completes whatever it wanted to do, it releases the lock. And meanwhile other threads can either sleep or spinlock.

What does the above quote mean by "any thread can usually release the mutex no matter which thread originally took the mutex."?

What's the point that I am missing?

2

2 Answers

5
votes

This may differ between different thread implementations, but since you've tagged your question with "pthreads" I assume you're interested in pthread mutexes (and not vxworks mutexes, which is apparently what the link you provide describes).

So in pthreads the rule is that the same thread that locks a mutex must unlock it. You can set attributes on the mutex object whether you want an error to be generated if this rule is violated, or whether the result is undefined behavior (say, for debug vs. release builds). See the manpage for the pthread_mutexattr_settype function for details.

1
votes

The specification for unlocking a pthread_mutex_t by a thread that wasn't the one that locked it depends on the mutex type (at best it returns an error):

Attempting to unlock a mutex on a thread that didn't lock it is undefined behavior for the following mutex types:

  • PTHREAD_MUTEX_NORMAL
  • PTHREAD_MUTEX_DEFAULT

Attempting to unlock a mutex on a thread that didn't lock it returns an error (EPERM) for these types:

  • PTHREAD_MUTEX_ERRORCHECK
  • PTHREAD_MUTEX_RECURSIVE

See http://pubs.opengroup.org/onlinepubs/007904875/functions/pthread_mutex_lock.html for details.

The bottom line is that it's never OK to unlock a mutex on a different thread, even if things seem to work.