【问题标题】:Synchronization among 2 threads in linux pthreadslinux pthreads中2个线程之间的同步
【发布时间】:2010-01-25 22:29:58
【问题描述】:

在 linux 中,如何在 2 个线程之间进行同步(在 linux 上使用 pthreads)? 我想,在某些情况下,一个线程会阻塞自己,然后再由另一个线程恢复。在 Java 中,有 wait()、notify() 函数。我正在 pthreads 上寻找相同的东西:

我读过这个,但它只有互斥锁,有点像 Java 的同步关键字。那不是我要找的。 https://computing.llnl.gov/tutorials/pthreads/#Mutexes

谢谢。

【问题讨论】:

    标签: linux pthreads


    【解决方案1】:

    您需要一个互斥体、一个条件变量和一个辅助变量。

    在线程 1 中:

    pthread_mutex_lock(&mtx);
    
    // We wait for helper to change (which is the true indication we are
    // ready) and use a condition variable so we can do this efficiently.
    while (helper == 0)
    {
        pthread_cond_wait(&cv, &mtx);
    }
    
    pthread_mutex_unlock(&mtx);
    

    在线程 2 中:

    pthread_mutex_lock(&mtx);
    
    helper = 1;
    pthread_cond_signal(&cv);
    
    pthread_mutex_unlock(&mtx);
    

    您需要辅助变量的原因是条件变量可能会受到spurious wakeup 的影响。它是帮助变量和条件变量的组合,可为您提供准确的语义和高效的等待。

    【讨论】:

    • 感谢您的好榜样。但是如果线程 1 在 pthread_cond_wait() 中,它会锁定 &mtx(因为它执行了 'pthread_mutex_lock' 行)。那么线程2如何获取&mtx上的锁并执行pthread_cond_signal()呢?
    • @n179911 - 请注意 pthread_cond_wait() 如何将互斥锁作为参数包含在内;它使用它来解锁/锁定互斥锁。从我的盒子的手册页“pthread_cond_wait 原子地解锁互斥锁(根据 pthread_unlock_mutex)并等待条件变量 cond 发出信号。在返回调用线程之前,pthread_cond_wait 重新获取互斥锁(根据 pthread_lock_mutex)”跨度>
    【解决方案2】:

    您还可以查看自旋锁。尝试以 man/google pthread_spin_init、pthread_spin_lock 为起点

    根据您的特定应用程序,它们可能比互斥锁更合适

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多