0
線程阻塞比等待更好嗎?有區別嗎?在2線程的情況下有條件變量和互斥鎖還是隻是互斥鎖更好?
場景1只是讓線程2豬全局變量k,直到它完成它。場景2展示了多於2個線程的真實世界多線程場景。
方案1:
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);
}
方案2:
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);
}
}
謝謝李!我同意場景1似乎不現實 – Cal
愛你的名字。 –