atomic_ref
safety should be based on operations that "potentially conflict" rather than lifetimeSection: 32.5.7 [atomics.ref.generic] Status: NAD Submitter: Billy O'Neal III Opened: 2020-09-12 Last modified: 2024-06-28
Priority: 3
View all other issues in [atomics.ref.generic].
View all issues with NAD status.
Discussion:
Consider the following program:
#include <atomic> #include <iostream> #include <thread> using namespace std; int main() { int i{500}; atomic_ref atom{i}; i += 500; thread t1{[&atom] { for (int val{0}, x{0}; x < 70;) { if (atom.compare_exchange_weak(val, val + 10)) { ++x; }}}}; thread t2{[&atom] { for (int val{0}, y{0}; y < 29;) { if (atom.compare_exchange_weak(val, val + 1)) { ++y; }}}}; t1.join(); t2.join(); cout << i << endl; // 1729 }
Technically this program has undefined behavior. 32.5.7 [atomics.ref.generic] p3 says
that, during the lifetime of any atomic_ref
referring to an object, that the object
may only be accessed through the atomic_ref
instances. However, in this example the
atomic_ref
is constructed before the i+=500
and is not destroyed before the
print, even though we have a happens-before relationship between the atomic and non-atomic
'phases' of access of the value.
#include <atomic> #include <iostream> #include <thread> using namespace std; int main() { int i{500}; i += 500; { atomic_ref atom{i}; thread t1{[&atom] { for (int val{0}, x{0}; x < 70;) { if (atom.compare_exchange_weak(val, val + 10)) { ++x; }}}}; thread t2{[&atom] { for (int val{0}, y{0}; y < 29;) { if (atom.compare_exchange_weak(val, val + 1)) { ++y; }}}}; t1.join(); t2.join(); } // destroy atom cout << i << endl; // 1729 }
We should probably get SG1 on record clarifying whether they intend the first program to be acceptable.
I can think of a reason to for atomic_ref
's ctor to do something (zeroing out padding), but
in our implementation it does nothing. I can't think of any reason for atomic_ref
's dtor to
do anything.
[2020-09-29; Priority to P3 after reflector discussions; Status set to "SG1"]
[St. Louis 2024-06-28; SG1 confirm the intent and recommend NAD.]
[St. Louis 2024-06-28; LWG: Status changed: Open → NAD.]
Proposed resolution: