![](/img/trans.png)
[英]How do I add different size of new array to an old array using a for loop?
[英]When using CAS (Compare And Swap), how do I ensure the old value is actually old?
考慮以下:
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));
}
我需要一種將* target讀入局部變量的方法,並確保該局部變量不會被簡單地*目標所優化。 易失性答案嗎?
是的,那正是volatile
所做的。
int grab_next_target(volatile int *target) {
...
int old = *target; // Guaranteed to access "target" exactly once
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.