如果互斥量已经被锁定,那么 pthread_mutex_lock(pthread_mutex_t *mutex);阻塞线程并同时 return 一个值?

If a mutex is already locked how can pthread_mutex_lock(pthread_mutex_t *mutex); block the thread and still return a value at the same time?

The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.

我的问题是,如果互斥锁已经被锁定,并且我们调用 pthread_mutex_lock(),这个函数 return 是一个值,即使线程被阻塞,还是 return块后的值?

我的问题的说明。

会发生什么? pthread_mutex_lock() return 它的值什么时候传给第二个线程?

是在互斥体被第一个线程解锁之后吗?或者,它 return 它的值会阻塞第二个线程吗?

描述意味着该函数将阻塞,直到互斥量被解锁(由其先前的所有者),然后它锁定互斥量,并且仅在此之后 returns。现在,函数的调用者是锁的所有者。

对您的问题的简短回答:pthread_mutex_lock(&mutex) 不会 return 一个值,直到线程在获得锁后解除阻塞。但是,您的代码只看到一个函数调用,感知一个直接的 return 值。

这里有更多的解释。

关于 return 个值:

  • 如果函数 pthread_mutex_lock(&mutex) return 为零,您可以相信线程已锁定 mutex: 别忘了解锁!

  • 如果方法 return 是 non-zero error codemutex 没有被你的线程锁定,你不应该做 a对应解锁

你的代码调用的视角 pthread_mutex_lock(&mutex):

  • 如果 mutex 未锁定,pthread_mutex_lock(&mutex) 将锁定 mutex 和 return 立即归零。

  • 如果 mutex 已经被另一个线程 锁定 ,该函数将阻塞,直到您的线程获得锁定mutex 然后 return 零。但是,从您的代码的角度来看,只看到一个 return 是一个值的函数调用:线程中的代码不会注意到它已被阻止。当然,除非您在函数调用周围放置计时器。

  • 如果 mutex 已被您的线程 锁定 ,函数将死锁。默认情况下,互斥量是不可重入的,您必须避免将其锁定在已经锁定的上下文中,例如递归。 我将如何执行重入锁定排除在范围之外。在这种情况下,函数根本就不会 returns.

  • 如果 mutex 由于任何原因不能被锁定,函数立即 returns 与 non-zero error code.