admin管理员组文章数量:1405765
How to atomically compare and store the value it's compared with if they aren't equal. The below code is not able to achieve this operation atomically
#include <iostream>
#include <atomic>
int main() {
static std::atomic<int> AT(23);
int a = 32;
if (AT.load() != a) {
std::cout << "not equal" << std::endl;
AT.store(a);
}
}
How to atomically compare and store the value it's compared with if they aren't equal. The below code is not able to achieve this operation atomically
#include <iostream>
#include <atomic>
int main() {
static std::atomic<int> AT(23);
int a = 32;
if (AT.load() != a) {
std::cout << "not equal" << std::endl;
AT.store(a);
}
}
Share
Improve this question
edited Mar 8 at 6:24
Nate Eldredge
59.5k6 gold badges71 silver badges113 bronze badges
asked Mar 8 at 5:57
HarryHarry
3,2681 gold badge24 silver badges46 bronze badges
25
|
Show 20 more comments
1 Answer
Reset to default 6You don't need to check the value in advance if all you want to know is whether setting it has changed the value, you can just use the exchange
function to set the new value:
#include <iostream>
#include <atomic>
int main() {
static std::atomic<int> AT(23);
int a = 32;
if (AT.exchange(a) != a) {
std::cout << "not equal" << std::endl;
}
}
If the value hasn't changed, resetting it to the same value shouldn't matter.
本文标签: catomically compare and store if not equalStack Overflow
版权声明:本文标题:c++ - atomically compare and store if not equal - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744902151a2631407.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
a
andAT
. Otherwise, you will still end up with a potential race condition (unlessa
is a constant) – Pepijn Kramer Commented Mar 8 at 6:06a
is not being concurrently written, so it is effectively a constant for the purposes of this code. – Nate Eldredge Commented Mar 8 at 6:09AT.store(a);
? I don't see that it is. IfAT
has a value different froma
, the store should be done. IfAT
has the valuea
, then storing that value back has no observable effect. Am I missing something? – Nate Eldredge Commented Mar 8 at 6:11if (AT.exchange(a) != a) { /* it changed */ }
– Nate Eldredge Commented Mar 8 at 6:30a
too? – Pepijn Kramer Commented Mar 8 at 6:45