用条件变量替换忙等待

时间:2015-05-16 09:29:31

标签: pthreads

如何用条件变量替换下面的忙等待?

while (this_thread != pthread_self()){
        pthread_mutex_lock(&lock);
        if(this_thread == -1)
            this_thread = get_id();
        pthread_mutex_unlock(&lock);
    }

谢谢!

1 个答案:

答案 0 :(得分:2)

假设get_id()返回的值通过名为set_id()的函数设置,请参阅此伪代码:

全局

Mutex mutex
Condition cond
Id id

set_id(id_in)
{
  mutex_lock
  id = id_in
  cond_signal
  mutex_unlock
}

test()
{
  mutex_lock
  while ((this_thread = get_id()) != pthread_self())
    cond_wait
  mutex_unlock
}