Title
atomic_ref safety should be based on operations that "potentially conflict" rather than lifetime
Status
nad
Section
[atomics.ref.generic]
Submitter
Billy O'Neal III

Created on 2020-09-12.00:00:00 last changed 5 months ago

Messages

Date: 2024-06-28.22:23:03

[ St. Louis 2024-06-28; LWG: Status changed: Open → NAD. ]

Date: 2024-06-28.20:02:25

[ St. Louis 2024-06-28; SG1 confirm the intent and recommend NAD. ]

Date: 2020-09-15.00:00:00

[ 2020-09-29; Priority to P3 after reflector discussions; Status set to "SG1" ]

Date: 2020-09-12.00:00:00

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:03adminsetmessages: + msg14225
2024-06-28 22:23:03adminsetstatus: open -> nad
2024-06-28 20:02:25adminsetmessages: + msg14218
2020-09-29 17:38:54adminsetmessages: + msg11489
2020-09-29 17:38:54adminsetstatus: new -> open
2020-09-12 00:00:00admincreate