Alternatives to make sure you are not grabbing the wrong lock include this much uglier GUARDED_BY macro, - http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
I'd say the extra lambda is a fair price to pay
Alternatives to make sure you are not grabbing the wrong lock include this much uglier GUARDED_BY macro, - http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
I'd say the extra lambda is a fair price to pay
thing->field.with([&](Field& field) {
use(field);
});
would become {
auto field = Mutex.locker(thing.field); // or thing.field.lock();
use(field);
}
or use(Mutex.locker(thing.field));
Yes, that requires you to understand destructors exist, but if you’re programming C++, that’s a given.I find that easier to understand (partly because the first doesn’t mention ‘lock’. I don’t think ‘with’ is the best name there)
Requiring a lambda capturing stuff and be passed around is not what I would call "pay less", when the alternative is just adding a block and instantiate a std::lock_guard
The change suggested in this part of this discussion is by user “Blackthorn” in https://news.ycombinator.com/item?id=35464828. It says:
> Neat idea. Though I think having to pass a lambda for anything you want to do with the fields is awful ergonomics.
> Maybe instead combine the two ideas. MutexProtected<T> but can be locked with MutexProtected<T>::lock() which returns a MutexLocked<T> object. That object then cleans up the lock when it goes out of scope, and also provides direct access to the enclosed type.
User “dietr1ch” replied in https://news.ycombinator.com/item?id=35465610 he wanted to pay with a lambda to make it clear a lock is taken.
I tried to clarify that Blackthorn‘s suggestion would make that clear without requiring that lambda.