Lock-Based/Lock-Free/Wait-Free之间区别

摘自 《The Art of Writing Efficient Programs》 https://learning.oreilly.com/library/view/the-art-of/9781800208117/

下面几个程序分别是 lock-based/wait-free/lock-free的

std::mutex m;
size_t count;
{
  std::lock_guard l(m);
  ++count;
}


std::atomic<size_t> count;
count.fetch_add(1, std::memory_order_relaxed);


std::atomic<size_t> count;
size_t c = count.load(std::memory_order_relaxed);

while (!count.compare_exchange_strong(c, c + 1,
     std::memory_order_relaxed, std::memory_order_relaxed)) {}

大致区别如下所说:wait-free不需要等待,lock-free不需要显示锁但是会有等待,因为在不断地进行重试。

We have just seen examples of the three main types of concurrent programs:

  • In a wait-free program, each thread is executing the operations it needs and is always making progress toward the final goal; there is no waiting for access, and no work needs to be redone.
  • In a lock-free program, multiple threads may be trying to update the same shared value, but only one of them will succeed. The rest will have to discard the work they have already done based on the original value, read the updated value, and do the computation again. But at least one thread is always guaranteed to commit its work and not have to redo it; thus, the entire program is always making progress, although not necessarily at full speed.
  • Finally, in a lock-based program, one thread is holding the lock that gives it access to the shared data. Just because it’s holding the lock does not mean it’s doing anything with this data, though. So, when the concurrent access happens, at most one thread is making progress, but even that is not guaranteed.

UPDATE: <Lock-free programming with modern C++ – Timur Doumler [ACCU 2017]>

lock-free: at least one thread will always make progress

wait-free: all threads will always make progress