C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: set_new_handler extension

From: Federico Kircheis <federico_at_[hidden]>
Date: Sun, 28 May 2023 18:02:40 +0200
>>> All you'd have to do is:
>>>
>>> std::lock_guard<std::mutex> lock(container.mutex());
>>> if(container.empty())
>>> {
>>> container.insert(....)
>>> }
>>
>> 1: Your example code has no such function.
>>
>> 2: All that would do is provoke UB. `empty` will attempt to lock the
>> mutex. Locking a `std::mutex` that is already locked by your thread
>> yields UB. You would need a `recursive_mutex`, which is basically the
>> thing I described with thread IDs wrapped in its own object. In short:
>> it adds overhead.
>
> Yes I corrected myself in the other post.
>
> But the overhead of mutices is not that bad also if it can save you from
> these treacherous race-conditions.
>

But your suggested containers hides the errors (as there are not more
data-races), and thus makes it more hard to find them.

Also I do not get why gpu is relevant.
With your code, the issue appears less often, thus it is still harder to
detect than with a class without the mutex.

And there is the issue when you get the reference to an object in the
container, still have this reference, and the container is changed in
another thread.


Can I propose an approach that

   * works with all containers of the standard library (and external
containers)
   * does not require recursive mutexes
   * gives the developer the possibility to minimize the number of
lokcs, but not avoid them accidentally
   * makes the developer aware that there is thread-synchonisations

?

The keywords are: "Inversion of control".

Just put the data to protect and the mutex in a structure together, and
let the user access it with a callback function.

For example

https://fekir.info/post/sharing-data-between-threads/#_bind-the-data-and-mutex-together


Federico

Received on 2023-05-28 16:02:49