2 つのスレッドを持つプログラムを想像してください。次のコードを実行しています (CAS はCompare and Swapを指します)。
// Visible to both threads
static int test;
// Run by thread A
void foo()
{
// Check if value is 'test' and swap in 0xdeadbeef
while(!CAS(&test, test, 0xdeadbeef)) {}
}
// Run by thread B
void bar()
{
while(1) {
// Perpetually atomically write rand() into the test variable
atomic_write(&test, rand());
}
}
0xdeadbeef が「テスト」に書き込まれないように、スレッド B がスレッド A の CAS を永続的に失敗させる可能性はありますか? それとも、自然なスケジューリングのジッタは、実際にはこれが決して起こらないことを意味するのでしょうか? スレッド A の while ループ内で何らかの作業が行われた場合はどうなるでしょうか。