1
は、次のことを考えてみましょう:CAS(Compare And Swap)を使用する場合、古い値が実際に古くなるようにするにはどうすればよいですか?
int grab_next_target(int* target) {
do {
/* Intention: store current value of *target into old, so as
to ensure that old never changes */
int old = *target;
/* get new value based on old -- note that old is assumed not to change here */
int new;
if (1 == old) { /* imagine that old is 1 so new is now 20 */
new = 20;
} else if (2 == old) {
new = 300;
} else if (3 == old) {
new = -20;
} else if (4 == old) {
new = 400;
}
/* but the compiler has optimized
old to just read from *target, so *target could be
changed by another thread to be 4. The CAS will succeed
and now target will hold the wrong value (it will hold 20, instead of 400) */
} while (!AO_compare_and_swap(target, old, new));
}
私はローカル変数に*ターゲットを読んで、ローカル変数が離れて単にターゲット*することに最適化されないことを保証する方法が必要です。揮発性は答えですか?