Dave Rager
Dave Rager

Reputation: 8160

How do you handle pthread_mutex_unlock failures?

Assuming a thread successfully calls pthread_mutex_lock, is it still possible that a call to pthread_mutex_unlock in that same thread will fail? If so, can you actually do something about it besides abort the thread?

if(pthread_mutex_lock(&m) == 0)
{
   // got the lock, let's do some work

   if(pthread_mutex_unlock(&m) != 0) // can this really fail?
   {
      // ok, we have a lock but can't unlock it?
   }
}

From this page, possible errors for pthread_mutex_unlock() are:

[EINVAL] The value specified by mutex does not refer to an initialised mutex object.

If the lock succeeded then this is unlikely to fail.

[EAGAIN] The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.

Really? For unlock?

The pthread_mutex_unlock() function may fail if:

[EPERM] The current thread does not own the mutex.

Again, if lock succeeded then this also should not occur.

So, my thoughts are if there is a successful lock then in this situation unlock should never fail making the error check and subsequent handling code pointless.

Upvotes: 12

Views: 9681

Answers (2)

geert3
geert3

Reputation: 7341

Well before you cry "victory". I ended up on this page looking for a reason why one of my programs failed on a pthread_mutex_unlock (on HP-UX, not Linux).

if (pthread_mutex_unlock(&mutex) != 0)
   throw YpException("unlock %s failed: %s", what.c_str(), strerror(errno));

This failed on me, after many million happy executions. errno was EINTR, although I just now found out that I should not be checking errno, but rather the return value. But nevertheless, the return value was NOT 0. And I can mathematically prove that at that spot I do own a valid lock.

So let's just say your theory is under stress, although more research is required ;-)

Upvotes: 4

dbeer
dbeer

Reputation: 7213

From the man page for pthread_mutex_unlock:

The pthread_mutex_unlock() function may fail if:

EPERM
The current thread does not own the mutex.

These functions shall not return an error code of [EINTR].

If you believe the man page, it would seem that your error case cannot happen.

Upvotes: 2

Related Questions