如何用条件变量替换下面的忙等待?
while (this_thread != pthread_self()){
pthread_mutex_lock(&lock);
if(this_thread == -1)
this_thread = get_id();
pthread_mutex_unlock(&lock);
}
谢谢!
答案 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
}