Re:MutexProtected: A C++ Pattern for Easier Concurrency
by kajaktum on Thursday April 06, 2023 @08:26AM
(#35467417)
Wait why is this a footgun?
[ Parent
| on HN ]
Re:MutexProtected: A C++ Pattern for Easier Concurrency
by akling on Thursday April 06, 2023 @08:56AM
(#35467736)
Because now you're holding a reference to `x` which is supposed to be protected by a mutex, even after the mutex is unlocked.
With the lambda-only API, it's much harder to make this mistake, since a temporary reference like this will still go out of scope at the end of the lambda expression.
Re:MutexProtected: A C++ Pattern for Easier Concurrency
by kajaktum on Thursday April 06, 2023 @01:15PM
(#35471425)
You specifically mentioned that this is a footgun:
> auto& x = state.locked()->x;
But I don't see how the reference here is gonna make a difference unless i am reading the lifetime of the lock here incorrectly. For example, this is perfectly fine right?
```
{
auto& x = state.locked()->x;
}
```
This will only be a problem if you have an outside struct that holds a reference
```
auto &a = "something";
{
auto& x = state.locked()->x;
a = x;
}
```
Which can still happen even if you use a lambda.
Re:MutexProtected: A C++ Pattern for Easier Concurrency
by MontagFTB on Thursday April 06, 2023 @09:03AM
(#35467805)
Holding the reference to a field that is protected by a mutex implies there is another thread out there that will race with your reference in either reading or writing it.
Even just a read is racy, as there is no “atomic read” of any size value if it is not already wrapped as atomic.