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.
The call to pthread_mutex_lock() may fail with the EDESTROYED error if the mutex is destroyed by the thread that was currently holding it. Mutex initialization using the PTHREAD_MUTEX_INITIALIZER does not immediately initialize the mutex.
The pthread_mutex_lock() function locks mutex. If the mutex is already locked, the calling thread will block until the mutex becomes available. So yes - your thread is blocked until the lock is available and it can obtain it.
pthread_mutex_lock() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.
An instance of a pthread_mutex_t should be defined globally and initialized when it is declared with the macro PTHREAD_MUTEX_INITIALIZER. There are three system calls which perform operations on a mutex, each of which takes a pointer to a pthread_mutex_t as an argument. int pthread_mutex_lock(pthread_mutex_t *mutex);
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 ;-)
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