使用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));
}
我需要一种方法将 *target 读入局部变量,并确保局部变量不会被优化为简单的 *target。挥发性是一个答案吗?
Consider the following:
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));
}
I need a way to read *target into a local variable and ensure that the local variable does not get optimized away to simply be *target. Is volatile an answer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这(而且正是这)就是 volatile 的作用。
Yes, that (and exactly that) is what
volatile
does.