【问题标题】:pthread_mutex_trylock() use to wait , until other lock has not releasedpthread_mutex_trylock() 用于等待,直到其他锁没有释放
【发布时间】:2017-11-16 03:47:43
【问题描述】:

在我的代码中,我使用 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);

【问题讨论】:

  • 在实际程序中,// Waiting for return type.是其他代码,还是只是注释,加锁和解锁操作是相邻发生的?

标签: c multithreading pthreads


【解决方案1】:

来自手册页

如果锁定,pthread_mutex_trylock() 函数将返回零 获取mutex引用的互斥对象。否则报错 返回数字表示错误。

// 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_lockpthread_mutex_trylockhere之间区别的问题 这是另一个example of handling multiple return values from pthread_try_lock()

【讨论】:

  • 我想等到线程 1 有锁,当线程 1 释放锁时,这个 while 循环应该结束。
【解决方案2】:

如果您想在另一个线程在其执行过程中达到某个点时唤醒特定线程,互斥锁通常不是合适的同步原语。替代方案是:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多