スレッドが待機するよりもブロックする方が良いですか? 違いはありますか?
シナリオ 1 では、スレッド 2 が完了するまでグローバル変数 k を独り占めしています。シナリオ 2 は、3 つ以上のスレッドを使用する、より現実的なマルチスレッド シナリオを示しています。
シナリオ 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);
}
}