想象一个有两个线程的程序。他们正在运行以下代码(CAS 指的是比较和交换):
// 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());
}
}
线程 B 是否有可能永久导致线程 A 的 CAS 失败,从而永远不会将 0xdeadbeef 写入“测试”?或者自然调度抖动是否意味着在实践中这永远不会发生?如果在线程 A 的 while 循环中完成了一些工作怎么办?