c - pthread_mutex_trylock() 用于等待,直到其他锁尚未释放

标签 c multithreading pthreads

在我的代码中,我使用 pthread_mutx_trylock() 来检查线程 1 是否已完成他的任务 工作并释放互斥锁吗?请让我知道它是否有效?

在线程 1 中:

     pthread_mutex_lock(&sync_wait);
     // Waiting for return type.
     pthread_mutex_unlock(&sync_wait);

在线程 2 中:

    while (pthread_mutex_trylock(&sync_wait) == 0) {
          }; // Wait until other thread has lock

    // Waiting till thread 1 sync wait lock has not released.
    pthread_mutex_unlock(&sync_wait);

最佳答案

来自手册页面

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.

// so this will loop forever once you aquire lock
    while (pthread_mutex_trylock(&sync_wait) == 0) {
              }; // Wait until other thread has lock

编辑:

这部分代码应该可以处理您的场景

while ( int ret = pthread_mutex_trylock( &sync_wait) )
{
  // Unable to get Mutex probably some other thread aquired it
  // sleep for some time usleep or even better use pthread_mutex_timedlock
  // Ideally possible ret values should have been handled but for now
  // this will do
}

是的pthread_mutex_unlock( );一旦完成工作

这是manpage 还有一个关于 pthread_mutex_lock 和 pthread_mutex_trylock 之间差异的问题 here 这是另一个 example of handling multiple return values from pthread_try_lock()

关于c - pthread_mutex_trylock() 用于等待,直到其他锁尚未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47321256/

相关文章:

c - c中的宏定义

ios - 如何在 build.sh 中正确设置编译器以在 iOS 中构建 VLC

multithreading - 快生产者和慢消费者

将 void* 转换为 double

我可以将文件描述符限制设置为每线程限制吗?

c - 当 fgets 在输入中间遇到 EOF 时会发生什么?

c - 寻找将十进制值转换为十六进制表示的宏

java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?

java - Socket和Thread,这段代码是做什么的?

python - Python Thread()删除换行符?