Lid*_*Guo 4 c unix linux pthreads
我阅读了Linux手册页和OpenGroup for pthread_mutex_lock并得到了这个:
如果成功,则pthread_mutex_lock()和pthread_mutex_unlock()函数将返回零,否则,将返回错误编号以指示错误.
如果获取了互斥锁引用的互斥对象上的锁,则pthread_mutex_trylock()函数将返回零.否则,返回错误号以指示错误.
jxh*_*jxh 10
在这种情况下,获取互斥锁意味着当时没有线程持有锁.如果互斥锁是递归的,则调用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 */
}
}
Run Code Online (Sandbox Code Playgroud)
在EAGAIN,EINVAL,ENOTRECOVERABLE,和EOWNERDEAD也发生同pthread_mutex_lock().有关更多信息,请参阅文档和手册页.