代码之家  ›  专栏  ›  技术社区  ›  n179911

linux pthreads中两个线程之间的同步

  •  3
  • n179911  · 技术社区  · 15 年前

    我想,在某些情况下,一个线程将阻止自己,然后,它将由另一个线程恢复。在Java中,有wait()、notify()函数。我正在pthreads上寻找相同的东西:

    我读过这篇文章,但它只有互斥,这有点像Java的synchronized关键字。这不是我想要的。 https://computing.llnl.gov/tutorials/pthreads/#Mutexes

    非常感谢。

    2 回复  |  直到 15 年前
        1
  •  10
  •   R Samuel Klatchko    15 年前

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

    在线程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 . 它是helper变量和condition变量的组合,为您提供精确的语义和高效的等待。

        2
  •  0
  •   lemic    14 年前