gpt4 book ai didi

c - pthread_mutex_trylock的返回和pthread_mutex_lock的返回有什么区别

转载 作者:IT王子 更新时间:2023-10-29 00:54:56 30 4
gpt4 key购买 nike

我阅读了 Linux 手册页和 OpenGroup 的 pthread_mutex_lock 并得到了这个:

If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions shall return zero, otherwise, an error number shall be returned to indicate the error.

The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error.

  1. 我被这两行弄糊涂了。如果你们都在成功时返回零,而在出错时返回非零,他们在哪里写两行?
  2. 我知道互斥量可以被锁定和解锁,但是获得互斥量是什么意思?

最佳答案

在这种情况下,mutex is acquired 意味着当时没有线程持有锁。如果互斥量是递归的,则对 pthread_mutex_trylock() 的调用将成功,除非它已被递归锁定太多次。

您可以将 pthread_mutex_trylock() 视为非阻塞调用,如果它会阻塞,它会返回一个错误。如果它返回成功,则意味着您拥有锁,就好像 pthred_mutex_lock() 成功返回一样。如果它因 EBUSY 而失败,则意味着其他人正在持有锁。如果失败并返回EOWNERDEAD,则锁被另一个线程持有,但那个线程已经死亡(实际上获取锁成功,但当前数据状态可能不一致)。如果它因 EAGAIN 而失败,则它被递归锁定了太多次。还有其他失败原因,但在那些情况下,锁没有被获取。

int error = pthread_mutex_trylock(&lock);
if (error == 0) {
/*... have the lock */
pthread_mutex_unlock(&lock);
} else if (error == EBUSY) {
/*... failed to get the lock because another thread holds lock */
} else if (error == EOWNERDEAD) {
/*... got the lock, but the critical section state may not be consistent */
if (make_state_consistent_succeeds()) {
pthread_mutex_consistent(&lock);
/*... things are good now */
pthread_mutex_unlock(&lock);
} else {
/*... abort()? */
}
} else {
switch (error) {
case EAGAIN: /*... recursively locked too many times */
case EINVAL: /*... thread priority higher than mutex priority ceiling */
case ENOTRECOVERABLE:
/*... mutex suffered EOWNERDEAD, and is no longer consistent */
default:
/*...some other as yet undocumented failure reason */
}
}

EAGAINEINVALENOTRECOVERABLEEOWNERDEAD 也发生在 pthread_mutex_lock()。有关更多信息,请咨询 documentationman page .

关于c - pthread_mutex_trylock的返回和pthread_mutex_lock的返回有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18393097/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com