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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744902151a4600040.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