Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

When using locks I'm more paranoid about misusing the lock and don't mind typing a bit more to make the code obvious. Also, it seems that good auto-completion for that pattern is simple to achieve.

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



It’s a fair price to pay, but I think the suggested change is better because it makes you pay less for the same benefit. It still would be obvious that there’s a lock, but the code would IMO be simpler:

  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)


> because it makes you pay less for the same benefit.

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


Fuller quote: “I think the suggested change is better because it makes you pay less for the same benefit”

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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: