C Pthreads 互斥值?

标签 c pthreads mutex

我正在编写一个包含几个关键部分的程序。问题是我需要在 if 语句中检查互斥锁的值。

我想做这样的事情:

if pthread_mutex(&mutex) == 0 // locked 
  // Do something
else if pthread_mutex(&mutex) == 1 // unlocked 
 // Do something else

这可能吗?

最佳答案

你想要pthread_mutex_trylock() .

来自该链接:

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/

相关文章:

c - Z-wave 协议(protocol)与 C : Questions about Z-wave frame structure & programming in general

创建 pthreads 线程池来处理 get 请求

c++ - pthreads 程序工作了一段时间然后停止

c++ - 如何在C/C++中设置获取互斥量的优先级

c++ - 如何最好地测试 Mutex 实现?

c++ - gcc/g++ 可以在忽略我的寄存器时告诉我吗?

c++ - 在 C 程序中解析 32 位整数

c - 为什么 execl 要求我在运行一个进程后点击 "Enter"?

c++ - 使用多线程时性能几乎没有提高

c++ - 有一种弱互斥概念吗?