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
  • Since you need to check 2 variables atomically. I think you can't use an atomic. You will need a std::mutex + std::scoped_lock to both a and AT. Otherwise, you will still end up with a potential race condition (unless a is a constant) – Pepijn Kramer Commented Mar 8 at 6:06
  • @PepijnKramer: I was assuming that a is not being concurrently written, so it is effectively a constant for the purposes of this code. – Nate Eldredge Commented Mar 8 at 6:09
  • 10 Is this actually observably different from an unconditional store AT.store(a);? I don't see that it is. If AT has a value different from a, the store should be done. If AT has the value a, then storing that value back has no observable effect. Am I missing something? – Nate Eldredge Commented Mar 8 at 6:11
  • 6 @Harry: If you do want to unconditionally store and see if there was a change, then what you want is simply if (AT.exchange(a) != a) { /* it changed */ } – Nate Eldredge Commented Mar 8 at 6:30
  • 2 @Harry in your real code base can other threads modify your a too? – Pepijn Kramer Commented Mar 8 at 6:45
 |  Show 20 more comments

1 Answer 1

Reset to default 6

You 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