线程阻塞比等待更好吗?有区别吗?
场景 1 只是让线程 2 占用全局变量 k 直到它完成。场景 2 呈现了更多具有 2 个以上线程的真实世界多线程场景。
场景一:
global_var k = 1;
Thread1()
{
//preliminary work
while (!done)
{
mutex_lock(handshake_k);
if (100 == k)
done = true;
mutex_unlock(handshake_k);
}
//continue executing
}
Thread2() {
//preliminary work
mutex_lock(handshake_k);
for (i=0; i <= 100; i++)
++k; ;
mutex_unlock(handshake_k);
}
场景二:
global_var k = 1;
Thread1()
{
//preliminary work
while (!done)
{
mutex_lock(handshake_k);
if (k < 100)
{
wait_cv(handshake_monitor_k); //unlocks handshake_k
//mutex exclusively locked here
}
else
done = true;
mutex_unlock(handshake_k);
}
//continue executing
}
Thread2()
{
//preliminary work
for (i=0; i <= 100; i++)
{
mutex_lock(handshake_k);
++k;
mutex_unlock(handshake_k);
}
}