-2

I've been using C++11 for several months, I've been enjoying most components of the C++11 standard library except those of the atomic-operations-related.

In my opinion, lock-free programming is too complicated to get it right, while lock-based programming is intuitive and easy to understand and follow. So, I have to consider the value of lock-free programming.

To fully understand lock-free programming and lock-based programming, I wonder:

What're the pros and cons of lock-free programming and lock-based programming?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 7
    I can think of some pros to reading the [Stack Overflow FAQ](http://stackoverflow.com/faq). This question is one of the cons of people _not_ reading it. – Lightness Races in Orbit Jan 28 '13 at 16:41
  • 1
    (Also, did you create this from some kind of template?) – Lightness Races in Orbit Jan 28 '13 at 16:41
  • 1
    http://stackoverflow.com/questions/1385468/is-lock-free-multithreaded-programming-making-anything-easier – Lightness Races in Orbit Jan 28 '13 at 16:45
  • 2
    One advantage of lock-free programming that's often overlooked is its benefit in creating algorithms that are reentrant (i.e. can be called from a signal handler that interrupted the same code operating on the same object). Things like atomic-increment-based counters are obviously in this class (where using a lock would not be signal-safe), but you can also think of constructing higher-level primitives such as reentrant+recursive mutexes using lock-free methods (of course, the thing you construct is then itself a lock :). – R.. GitHub STOP HELPING ICE Jan 28 '13 at 16:45
  • 1
    One advantage of lock-based programming is mind-sanity – David Rodríguez - dribeas Jan 28 '13 at 17:04

1 Answers1

2

Obviously, lock-free programming can be hard to get right. However, if someone else has alreaedy done something that operates in a lock-free manner (e.g. queue, list, vector, etc), then using that is clearly a great thing.

Locks will always make things slower - because you have to take the lock, THEN do the operaton you need to do on some shared object, and THEN release the lock - it inevitably takes longer than doing the same thing using the correct "lockless" operation.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 3
    Locks won't necessarily make an operation slower; typically, a lock-free operation will need to check for success and possibly retry, which might very well take longer than acquiring and releasing a lock. The point of a lock-free operation is that it doesn't block other threads, potentially improving overall performance. – Mike Seymour Jan 28 '13 at 17:50
  • Yes, perhaps poor choice of words by saying it's slower - but the overall performance is [when lockless is done right] bettter without locks. – Mats Petersson Jan 28 '13 at 17:55