我正在编写一个包含几个关键部分的程序。问题是我需要在 if 语句中检查互斥锁的值。
我想做这样的事情:
if pthread_mutex(&mutex) == 0 // locked
// Do something
else if pthread_mutex(&mutex) == 1 // unlocked
// Do something else
这可能吗?
最佳答案
来自该链接:
The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. ... Return values ... 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
所以你的代码应该是这样的:
pthread_mutex_t *m = /* ... */;
if (pthread_mutex_trylock(m) == 0)
{
/* Success! This thread now owns the lock. */
}
else
{
/* Fail! This thread doesn't own the lock. Do something else... */
}
关于C Pthreads 互斥值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3939806/