Created on 2020-09-12.00:00:00 last changed 17 months ago
[ St. Louis 2024-06-28; LWG: Status changed: Open → NAD. ]
[ St. Louis 2024-06-28; SG1 confirm the intent and recommend NAD. ]
[ 2020-09-29; Priority to P3 after reflector discussions; Status set to "SG1" ]
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. [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.
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2024-06-28 22:23:03 | admin | set | messages: + msg14225 |
| 2024-06-28 22:23:03 | admin | set | status: open -> nad |
| 2024-06-28 20:02:25 | admin | set | messages: + msg14218 |
| 2020-09-29 17:38:54 | admin | set | messages: + msg11489 |
| 2020-09-29 17:38:54 | admin | set | status: new -> open |
| 2020-09-12 00:00:00 | admin | create | |