C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: set_new_handler extension

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 29 May 2023 16:59:03 -0400
On Mon, May 29, 2023 at 4:18 PM Tony V E via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Step one for fixing the thread safety problems of sharing data between threads,
> is to not share data between threads.
>
> This also works great for GPUs.
>
> Adding thread-safe containers just encourages the wrong approach.

Note that step 2 is often the use of very particular lanes of
inter-thread communication that are tailored to access patterns and
use cases. `promise/future` is a near-perfect example: it's a tool
that "shares" data by forwarding a single object (or exception) from
the producer of that data to its asynchronous consumer(s). That is the
totality of its job, and it allows no other method of interaction.

Most containers are not designed for these particular use cases;
they're too open-ended with no recognition of the way you intend to
use them. You *could* use a "thread-safe" version of `optional<T>` or
`variant<monostate, T, E>`as a shared promise/future. But this opens
up a bunch of possibilities: the "source" thread could try to read
data set by the "destination" thread. Since these are generic tools,
there is no mechanism to prevent the conceptually wrong kind of
access.

By using these generalized containers instead of specialized tools,
you open yourself up to bugs that simply cannot exist if you used the
right tool. That makes it harder to debug problems, since the way the
system is meant to be used is not baked into the API. If code that's
supposed to provide the value reading from the set data intentionally
inverting the flow of information, or was the user just being lazy and
didn't want to keep an extra copy of the value around to read from
later? `promise` doesn't give you either option: the holder of a
promise cannot read the value, and it can't even get a `future` of it
(if you already got one earlier). So if the code wants to invert
information flow, it's going to have to use something else, and if the
user wanted to just read what it had set, it has to keep a copy since
`promise` doesn't let you do that.

Received on 2023-05-29 20:59:16