在这种情况下,获得互斥锁意味着当时没有线程持有锁。如果互斥锁是递归的,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 */
}
}
, EAGAIN
,EINVAL
和ENOTRECOVERABLE
也EOWNERDEAD
发生在pthread_mutex_lock()
. 有关更多信息,请参阅文档和手册页。