C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: set_new_handler extension

From: Thiago Macieira <thiago_at_[hidden]>
Date: Thu, 01 Jun 2023 08:54:40 -0700
On Thursday, 1 June 2023 07:27:33 PDT Phil Bouchard wrote:
> > This may have no data race and thus cause no data corruption, but it's not
> > what was required because the states may have changed. If this is still
> > allowed, then just using the container in question does *not* confer
> > thread- safety. And therefore, if it is allowed to compile, how do you
> > propose we teach everyone *how* to write code to actually make it
> > thread-safe?
> You add some type trait allowing the compiler to determine whether the
> class is a "thread-safe" class or not.

You're still missing the forest for the trees. It feels like you're being
intentionally obtuse, though I do know you're an intelligent person and
therefore there must be an alternative explanation.

I repeat:
 if (!container.empty())
     container.push_back(1);

This causes no data corruption, but may end up with a list with multiple
elements "1" if multiple threads raced the check for empty(), concluded that
it was empty, then each added an element.

So I ask you one last time; how do you teach people that they must acquire a
lock on the empty() check?

You said that this could be automatically detected by the compiler and kept on
scope. So let me modify the problem: if the container is empty, add 0. Then
add the thread's ID, regardless of whether it was empty or not.

Which of the two implementations below is "correct" ?

Option 1:
  if (container.empty()) { // magically acquires lock
      container.push_back(0);
      container.push_back(thread_id);
  } else {
      container.push_back(thread_id);
  }
  // lock released here

Option 2:
  if (container.empty()) // magically acquires lock
      container.push_back(0);
  // lock released here
  container.push_back(thread_id); // acquires lock again
  // lock released again

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-06-01 15:54:42