使用 compre_exchange 和 c++20 比较值表示吗? (为什么这个例子不同意)
Does using compre_exchange with c++20 compare the value representations? (why doesn't this example agree)
由此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).
因此使用C++20
,下面代码中的while
循环一定是无限的,但它是有限的。我是不是错了或者发生了什么事
#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";
}
此更改(使用值表示而不是对象表示)是作为 P0528R3 (the motivation and story can be found in P0528R0). As you can see under cppreference's compiler support 的一部分完成的,gcc 和 clang 均未实现此功能。 MSVC 在 19.28 上运行,但在编译器资源管理器上不可用,所以我目前无法检查以验证。
所以目前,您正在有效地验证旧行为。
由此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).
因此使用C++20
,下面代码中的while
循环一定是无限的,但它是有限的。我是不是错了或者发生了什么事
#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";
}
此更改(使用值表示而不是对象表示)是作为 P0528R3 (the motivation and story can be found in P0528R0). As you can see under cppreference's compiler support 的一部分完成的,gcc 和 clang 均未实现此功能。 MSVC 在 19.28 上运行,但在编译器资源管理器上不可用,所以我目前无法检查以验证。
所以目前,您正在有效地验证旧行为。