This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of SG1 status.
Section: 33.5.7 [atomics.ref.generic] Status: SG1 Submitter: Billy O'Neal III Opened: 2020-09-12 Last modified: 2020-09-29
Priority: 3
View all other issues in [atomics.ref.generic].
View all issues with SG1 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. 33.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.
The user would instead have to write:#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"]
Proposed resolution: