C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 29 Jun 2023 10:05:35 +0100
On Thu, Jun 29, 2023 at 6:51 AM Federico Kircheis wrote:
>
> Also it "leaks" the internal object, for example
>
> ----
> auto vec& = *(g->vec.Reserve());
> // bypassing mutex and still access to internal data
> ----
>
> and also with
>
> ----
> int& j = vec->at(0);
> ----
>
> I think such classes are doomed, because hiding the fact there is a
> synchronisation mechanism is rarely a good idea for low-level
> operations/generic classes.


Then maybe give it a little compiler support, for example the following code:

void Func(void)
{
    auto mylock = global.synchronize();
    auto &r = *mylock;

    r.DoSomething():
}

could become:

void Func(void)
{
    synchro_ref(global) r; // This defines an Lvalue reference called 'r'

    r.DoSomething():
}

That is to say, when 'synchro_ref' is applied to a
'std::synchronized_value' in the definition of a non-static local
variable, it gives you an L-value reference whose lifetime is exactly
the same as an invisible locking object. Perhaps also give access to
the invisible locking object:

void Func(void)
{
    synchro_ref(global) r; // This defines an Lvalue reference called 'r'

    r.DoSomething():

    auto mylock = synchro_ref_get_lock(r);
    mylock->release();

    r.DoSomething(); // Don't do this! The lock isn't locked!

     mylock->relock();

    r.DoSomething(); // this is safe because we relocked it
}

Received on 2023-06-29 09:05:46