我想使用原子比较和交换,而不是等于,我只想在内存位置不等于旧值时交换。在 C 中可以吗?
最佳答案
这个怎么样:
void compare_and_swap_if_not_equal(word_t const required_non_value, word_t const new_value, word_t* ptr_to_shared_variable) {
for (;;) {
word_t const snapshot_value = *ptr_to_shared_variable;
if (required_non_value == snapshot_value) {
break;
// or (sleep and) 'continue;', if you want to wait for the stored value to be different
// -- but you might of course miss a transient change to a different state and back.
} else {
if (compare_and_swap_if_equal(ptr_to_shared_variable, snapshot_value, new_value)) {
// we know the stored value was different; if this 'theory' still matches reality: swap! done!
break;
}
}
}
}
未经测试。未编译。使用'const'是因为我喜欢这样:)。 'word_t' 是一个类型占位符,我不知道真正的类型应该是什么。而且我不知道在 stdatomic.h 中如何调用“compare_and_swap_if_equal”。
(补充)atomic_compare_exchange_weak() 是门票。出于某种原因,它需要一个指向“预期”参数的指针,因此您必须将上面的代码修改为
if (atomic_compare_exchange_weak(ptr_to_shared_variable, &snapshot_value, new_value)) ...
“弱”版本应该在上面的代码中工作;虚假地返回“false”只会在循环中增加另一次旅行。仍未编译,未经测试;不要在家里依赖这个代码。
关于c - 原子比较(不等于)和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12755130/