问题描述
我阅读了Linux手册页和pthread_mutex_lock
的OpenGroup并获得了此信息:
I read the Linux man page and OpenGroup for pthread_mutex_lock
and get this:
如果获取了互斥锁引用的互斥对象上的锁,则pthread_mutex_trylock()函数应返回零.否则, 返回错误号以指示错误.
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.
- 我对这两行感到困惑.如果您在成功时都返回零,而在错误时都返回非零,那么他们在哪里写在两行中?
- 我知道互斥锁可以锁定和解锁,但是获取互斥锁是什么意思?
- I was confused by these two lines. If you both return zero when sucess and return non-zero when error, where do they write this in two lines?
- I know mutex can be lock and unlock, but what does a mutex is acquired mean?
推荐答案
在这种情况下,获取 mutex 表示当时没有线程持有该锁.如果互斥量是递归的,则对pthread_mutex_trylock()
的调用将成功,除非它被递归锁定了太多次.
In this context mutex is acquired means that there was no thread holding the lock at the time. If the mutex is recursive, the call to pthread_mutex_trylock()
will succeed unless it has been recursively locked too many times.
您可以将pthread_mutex_trylock()
视为一个非阻塞调用,如果该阻塞将被阻塞,则返回一个错误.如果返回成功,则表示您拥有锁,就像pthred_mutex_lock()
成功返回一样.如果它失败并显示EBUSY
,则表示其他人正在持有该锁.如果使用EOWNERDEAD
失败,则该锁由另一个线程持有,但该线程已死(获取该锁实际上已成功,但是当前数据状态可能不一致).如果使用EAGAIN
失败,则将其递归锁定太多次.还有其他失败原因,但是在这种情况下,尚未获得锁定.
You can think of pthread_mutex_trylock()
as a non-blocking call, where if it would have blocked, it returns with an error instead. If it returns success, it means you have the lock as if pthred_mutex_lock()
returned successfully. If it fails with EBUSY
it means some other is holding the lock. If it fails with EOWNERDEAD
, the lock was held by another thread, but that thread had died (getting the lock actually succeeded, but the current data state may not be consistent). If it fails with EAGAIN
it was locked recursively too many times. There are other failure reasons, but in those cases, the lock has not been acquired.
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()
一起出现.有关更多信息,请参阅文档和手册页.
The EAGAIN
, EINVAL
, ENOTRECOVERABLE
, and EOWNERDEAD
also happen with pthread_mutex_lock()
. For more information, consult the documentation and man page.
这篇关于pthread_mutex_trylock的返回和pthread_mutex_lock的返回之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!