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

Created on 2020-09-12.00:00:00 last changed 2 weeks ago

Messages

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
2020-09-12 00:00:00admincreate