开发者

Threads trying to acquire pthread_mutex_lock(&mutex) What happens if they don't get the lock?

开发者 https://www.devze.com 2023-02-15 23:05 出处:网络
C Programming: What happens when a thread tries to acquire a mutex lock, and fails 开发者_JS百科to get it?

C Programming:

What happens when a thread tries to acquire a mutex lock, and fails 开发者_JS百科to get it?

Does it go to sleep?

Will the thread be woken up when pthread_mutex_unlock(&mutex); is called?

Then try to obtain the lock again?


From the man page:

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.


Yes, it is a blocking call and will block until it gets the lock.

The non-blocking version is pthread_mutex_trylock(pthread_mutex_t *mutex) and will return EBUSY if someone else has the lock, or 0 if it got the lock. (Or some other error, of course)


Normally, pthread_mutex_lock cannot return until it acquires the lock, even if this means that it never returns (deadlock). There are a few notable exceptions though:

  • For recursive mutexes, it can return EAGAIN if the maximum reference count would be exceeded.
  • For error-checking mutexes, it can return EDEADLK if the thread tries to lock a mutex it already holds a lock on.
  • For robust mutexes, it can return EOWNERDEAD if another process died while holding the (shared) mutex. In this case, despite getting an error return, the caller holds the mutex lock and can mark the mutex-protected state valid again by calling pthread_mutex_consistent.
  • For robust mutexes whose owner died and for which the new owner called pthread_mutex_unlock without calling pthread_mutex_consistent first, it will return ENOTRECOVERABLE.

There may be a few cases I missed. Note that none of these apply to normal mutexes (PTHREAD_MUTEX_NORMAL type) without the robust attribute set, so if you only use normal mutexes, you can reasonably assume the call never returns without succeeding.


From the POSIX standard:

If the mutex is already locked, the calling thread shall block until the mutex becomes available.

(...)

If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.

Where the "resulting in" clause is necessary because

(In the case of PTHREAD_MUTEX_RECURSIVE mutexes, the mutex shall become available when the count reaches zero and the calling thread no longer has any locks on this mutex.)

0

精彩评论

暂无评论...
验证码 换一张
取 消