原子比较(不等于)和swap [英] atomic compare(not equal) and swap
问题描述
我想使用原子比较和交换,但不是等于,我想只交换如果存储器位置不等于旧值。是否有可能用C?
I want to use atomic compare and swap, but instead of equal to, I want to swap only if the memory location is not equal to the old value. Is it possible in 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;
}
}
}
}
未经检验。未编译。使用,因为我喜欢这样:)的常量。 word_t是一种占位符,我不知道真正的类型应该是什么。我不知道怎么样'compare_and_swap_if_equal被称为stdatomic.h。
Untested. Uncompiled. The 'const' used because I like it that way :). 'word_t' is a type placeholder, I don't know what the real type should be. And I don't know how what 'compare_and_swap_if_equal' is called in stdatomic.h.
(添加)atomic_compare_exchange_weak()是门票。出于某种原因,它需要一个指向预期的说法,所以你必须修改上述code到
(added) atomic_compare_exchange_weak() is the ticket. For some reason, it takes a pointer to the 'expected' argument, so you'll have to modify above code to
如果(atomic_compare_exchange_weak(ptr_to_shared_variable,&安培; snapshot_value,NEW_VALUE))...
if (atomic_compare_exchange_weak(ptr_to_shared_variable, &snapshot_value, new_value)) ...
弱版本应该在上面code工作;返回假不合逻辑只会增加另一次环路之旅。仍然未编译的,未经检验的;不靠家里此code。
The 'weak' version should work in the above code; returning 'false' spuriously will only add another trip around the loop. Still uncompiled, untested; don't rely on this code at home.
这篇关于原子比较(不等于)和swap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!