用条件变量代替忙等待
Replace busy waiting with condition variable
如何用条件变量替换下面的忙等待?
while (this_thread != pthread_self()){
pthread_mutex_lock(&lock);
if(this_thread == -1)
this_thread = get_id();
pthread_mutex_unlock(&lock);
}
谢谢!
假设 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
}
如何用条件变量替换下面的忙等待?
while (this_thread != pthread_self()){
pthread_mutex_lock(&lock);
if(this_thread == -1)
this_thread = get_id();
pthread_mutex_unlock(&lock);
}
谢谢!
假设 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
}