From this link
Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation). Otherwise, loads the actual value stored in *this into expected (performs load operation).
Hence using C++20
, the while
loop in the following code must be infinite but It's finite. Am I wrong or what's happening
#include <atomic>
#include <iostream>
struct S {
char a{};
int b{};
};
bool operator==(const S& lhs, const S& rhs) {
return lhs.a == rhs.a && lhs.b == rhs.b;
}
int main() {
S expected{ 'a', 2 };
std::atomic<S> atomicS{ S{'a', 2} };
reinterpret_cast<unsigned char*>(&(atomicS))[1] = 'e';
reinterpret_cast<unsigned char*>(&(expected))[1] = 'f';
while (atomicS.compare_exchange_strong(expected, S{ 'a',2 }));
std::cout << "\nfinished";
}
This change (to use value representation instead of object representation) was done as part of P0528R3 (the motivation and story can be found in P0528R0 ). As you can see under cppreference's compiler support , neither gcc nor clang implement this feature yet. MSVC does on 19.28, but that's not available on compiler explorer, so I cannot check that to verify at the moment.
So at the moment, you're effectively verifying the old behavior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.