C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Helper class to make safe a thread-unsafe class

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 28 Jun 2023 19:56:04 -0400
On Wed, Jun 28, 2023 at 7:13 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> On Thu, Jun 29, 2023 at 12:05 AM Ville Voutilainen via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> >>
> > > Indeed. This is boost::synchronized_value<T>.
> >
> > There's also a synchronized_value in
> > https://open-std.org/JTC1/SC22/WG21/docs/papers/2023/n4953.pdf
> > I thought Jonathan mentioned that earlier?
>
>
> It turns out that the GNU compiler g++ version 13 already has this
> under std::experimental.
>
> Looking through the implementation of boost:synchronized_value, it
> looks like it uses a regular mutex. My own implementation of my own
> class uses a recursive mutex so that you can do stuff like:
>
> void Func2(void)
> {
> g_obj->push_back(78);
> }
>
> void Func(void)
> {
> auto mylock = g_obj.Reserve();
> mylock->push_back(73);
> mylock->push_back(71);
> Func2(); // This would cause thread-lock if the mutex weren't a
> recursive_mutex
> mylock->push_back(79);
> }
>
> I think a recursive_mutex is better here.

Code that does things like that should be broken.

The first principle of good thread-safe code is to not share stuff
across threads. If something must be shared across threads, it should
be designed to be shared for that particular purpose. If your use of
shared objects is so unstructured that you can't even stop *your own
thread* from double-locking such an object, then it seems pretty
unlikely you're writing good code.

We shouldn't pretend code is "thread-safe" just because you use a
mutex-based interface for some shared object.

Received on 2023-06-28 23:56:15